I need to replace the price in JavaScript string, but only if it is not a value of an attribute. The result should look like this:
'<span title="$30,000,000.50">$30,000,000.50</span>' // original
'<span title="$30,000,000.50">xxx</span>' // desired result
'bla bla bla $30,000,000.50 bla bla bla' // original
'bla bla bla xxx bla bla bla' // desired result
I define the price as a dollar sign, followed by a combination of digits, dots and commas:
/\$[\d,.]+/
That works fine. But when I try to exclude the occurences where this pattern is wrapped in quotes, it starts to behave funny:
'<span title="$30,000,000.50">$30,000,000.50</span>'.replace(/(?!=\")(\$[\d,.]+)(?!\")/gi, 'xxx');
// <span title="xxx0">xxx</span>
Notice that it replaced the value of title attribute, but it kept the last zero.
Can you please correct my code and tell me what I do wrong? Thank you.
You need a negative look ahead and a negative look behind. Unfortunately, JavaScript doesn’t support look behinds. However, using a technique from: http://blog.stevenlevithan.com/archives/mimic-lookbehind-javascript you can mimic this behavior.
http://jsfiddle.net/nachito/Wfdq6/1/