0

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 ?

2 Answers 2

1

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 + ']');
Sign up to request clarification or add additional context in comments.

2 Comments

ok, but what about this format "@[0], 0" into "@[1], 1" ? thx
@JozsefNaghi var regex = new RegExp('@\\[' + increment + '\\],\s' + increment, 'gi') html = html.replace(regex, '@[' + counter + '], ' + counter);
0

Use this way:

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

This makes use of the dynamic values.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.