Javascript: Regex part II

The tutor continues about regex in the context of Javascript.

In yesterday’s post I brought up regular expressions with an interactive example. Today, some more depth:

Let’s imagine an input string that means an amount of money. Likely, the amount includes a currency symbol; perhaps it’s

$1 117.89

or

€1 117.89

To Javascript, the presence of a currency symbol means the string is not a number. The same goes for the space between the digits. Therefore, if calculation is to be done on the number, it must be amended to

1117.89

Let’s imagine the input is contained in the string catch0, like so:

var catch0=”€1 117.89″;

Everything but the digits and decimal point needs to be removed. The replace() function can be used, as follows:

var catch1=catch0.replace(/[^0-9.]/g,””);

The replace() function must be applied to a string. It can use the following syntax:

thestring.replace(/to_be_replaced/,”replacement”);

For instance, let’s imagine the string

var mailstring=”mailatsomewhere.there”;

Further, let’s imagine that we want to replace at with @. We could do so as follows:

var numailstring=mailstring.replace(/at/, “@”);

Now, the value of numailstring is mail@somewhere.there

This doesn’t quite explain the workings of the example from last post, but it’s on the way. I’ll be continuing …:)

Source:

w3schools.com

Jack of Oracle Tutoring by Jack and Diane, Campbell River, BC.

Leave a Reply