Jozsef Naghi
Jozsef Naghi

Reputation: 1095

Replacing all occurences in a string in javascript issue

This is my js code:

html = html.replace("/["+increment+"]/gi", '[' + counter + ']');

where increment is 0 and counter is 1 or

html = html.replace("/[0]/gi", '[1]');

My version does not replace the [0] with [1] in my string. Why ?

Upvotes: 0

Views: 50

Answers (2)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167182

Use this way:

html = html.replace(new RegExp("\\["+increment+"\\]", "gi"), '[' + counter + ']');

This makes use of the dynamic values.

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

You need to use the RegExp constructor as the regex is dynamic

var regex = new RegExp("\\[" + increment + "\\]", 'gi')
html = html.replace(regex, '[' + counter + ']');

Also you could sanitize the dynamic variable if you want

if (!RegExp.escape) {
    //A escape function to sanitize special characters in the regex
    RegExp.escape = function (value) {
        return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&")
    };
}



//You could also escape the dynamic value it is an user input
var regex = new RegExp("\\[" + RegExp.escape(increment) + "\\]", 'gi')
html = html.replace(regex, '[' + counter + ']');

Upvotes: 1

Related Questions