Link to home
Start Free TrialLog in
Avatar of ncw
ncw

asked on

What are these regex supposed to do?

The html includes a span tag with id="productPrice" which wraps around a price with currency symbol, and the in-page javascript includes a variable called baseprice which is set to be the innerHTML of productPrice and therefore includes the currency symbol.

Can you tell me please what does the regex do in the following code?
document.getElementById('productPrice').innerHTML = baseprice.replace(/[+-]*(d+).(d+)/, total.toFixed(2));

Open in new window


The next alternative code is an extended version of the one above; Can you tell me please what does the next regex do?
document.getElementById('productPrice').innerHTML = baseprice.replace(/[+-]*(d+).(d+)/, total.toFixed(2).replace(/(d)(?=(d{3})+.)/g, "$1,"));

Open in new window


The code above does not seem to work, the following does except that it loses the currency symbol:
document.getElementById('productPrice').innerHTML = total.toFixed(2);

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Derek Jensen
Derek Jensen
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I suggest you to take a look to W3 schools tutorials (http://www.w3schools.com/js/js_obj_regexp.asp and http://www.w3schools.com/jsref/jsref_obj_regexp.asp). Th ToFixed JS function converts a number to a string, keeping the number of decimals you want (see http://www.w3schools.com/jsref/jsref_tofixed.asp).
@ncw wasn't asking what .toFixed() did, he asked what the regexes did, so I explained it. total.toFixed(2) was in the replace argv of .replace(). :-)
Avatar of ncw
ncw

ASKER

Many thanks!