0

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.

Adrian Rosca
  • 6,922
  • 9
  • 40
  • 57
  • maybe related : http://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format – Hacketo Aug 20 '15 at 10:01
  • This a duplicate of duplicate(s+), e.g. http://stackoverflow.com/questions/29120713/javascript-regular-expression-nothing-to-repeat – Wiktor Stribiżew Aug 20 '15 at 10:04

1 Answers1

4

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.

deceze
  • 510,633
  • 85
  • 743
  • 889