1

I'm trying to replace all occurences of {0}, {1}, {2}, etc in a string with Javascript.

Example string:

var str = "Hello, my name is {0} and I'm {1} years."; 

I'm tried the following to construct the regexp:

var regex1 = new RegExp("{" + i + "}", "g") var regex2 = new RegExp("\{" + i + "\}", "g") 

Both attempts throws the error:

Invalid regular expression: /{0}/: Nothing to repeat 

I use replace like this:

str.replace(regex, "Inserted string"); 

Found all kinds of StackOverflow posts with different solutions, but not quite to solve my case.

2

1 Answer 1

5

The string literal "\{" results in the string "{". If you need a backslash in there, you need to escape it:

"\\{" 

This will results in the regex \{..\}, which is the correct regex syntax.

Having said that, your approach is more than weird. Using a regex you should do something like this:

var substitues = ['foo', 'bar']; str = str.replace(/\{(\d+)\}/, function (match, num) { return substitutes[num]; }); 

In other words, don't dynamically construct a regex for each value; do one regex which matches all values and lets you substitute them as needed.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.