The below code gives the error:
var a = "hello {0} world";
a.replace(/{0}/g, "little");
But this one works:
var a = "hello {str} world";
a.replace(/{str}/g, "little");
Why do we get this error?
Because {n} (with n being a positive integer) is quantifier syntax, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Quantifiers
You don’t want the curly braces to have their “special meaning” here, but want them treated as plain characters - so you should escape them.
a.replace(/\{0\}/g,"little")
Your argument to replace() is a regular expression.
In particular, braces { and } are regular expression metacharacters (they are a range quantifier).
You must escape (with \) the braces in your regular expression for this to work.
For example, this:
a.replace(/\{0\}/g, "little");
would work. This would treat the braces literally.
The specific error message you get:
SyntaxError: Invalid regular expression: /{0}/: Nothing to repeat
is because the engine expects some text to precede the quantifier, so for example, x{0} would be a valid argument as a regular expression.
In the other case, using
a.replace(/{str}/g, "little");
does work, since the braces lose their special meaning as metacharacters, and get treated literally. Range quantifiers must take the form {n}, {n,} or {n,m} where n and m are integers.