Question

I need all numeric hash tags replace with actual number.

Consider this code:

var test = '#1 *#1*#137-#137 *Math.PI';

test = test.replace(/#1/g, '666');
test = test.replace(/#137/g, '444');

It will return:

666 *666*66637-66637 *Math.PI

the first regexp for #1 will replace #137 as well, because it contains #1.

The goal is:

666 *666*444-444 *Math.PI

Here is JSFIDDLE: http://jsfiddle.net/U3eX2/

Any idea?

Was it helpful?

Solution

You just need a simple negative lookbehind:

var test = '#1 *#1*#137-#137 *Math.PI';

test = test.replace(/#1(?!\d)/g, '666');
test = test.replace(/#137/g, '444');

$('div').text(test);

http://jsfiddle.net/U3eX2/1/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top