1

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?

0

3 Answers 3

3

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

Comments

1

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.

Comments

1

Problem

The number inside a curly brace has a special meaning, it is quanitifier syntax.

Solution

You have to escape the curly braces with \{ \}

Here is an example

var b = "hello {0} world"; 
console.log(b.replace(/\{0\}/g,"little"));

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.