1

I would like to use .replace() function in JS to replace all occurencies of string "{5}".

I had no problems with letters in brackets but numbers just dont work if I call:

mystring.replace(/{\5}/g,'replaced') 

nothing happens. Please can you help me with right syntax?

2
  • 4
    Braces are special regex characters, you need to escape them, numbers are not. Commented May 4, 2014 at 21:47
  • Why not escape the number and not the brackets ? Commented May 4, 2014 at 21:48

3 Answers 3

3

It looks like you have a problem with escaping. I'm pretty sure \5 is a backreference. You should instead be escaping the curly braces and not the number.

'Something {5} another thing'.replace(/\{5\}/g, 'replaced'); // -> Something replaced another thing 

Additional Note: Just in case you're looking for a generalized string formatting solution, check out this SO question with some truly awesome answers.

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

1 Comment

thanks, I got confused because ".replace(/{B}/g,'replaced')" worked without escaping brackets...
2

Is there a special reason you are preceding the number with a backslash? If your intention is to match against the string "{5}", "{" and "}" are the special characters that should be escaped, not the character "5" itself!

According to MDN:

A backslash that precedes a non-special character indicates that the next character is special and is not to be interpreted literally. For example, a 'b' without a preceding '\' generally matches lowercase 'b's wherever they occur. But a '\b' by itself doesn't match any character; it forms the special word boundary character.

The following code would work:

var str = "foo{5}bar{5}"; var newStr = str.replace(/\{5\}/g, "_test_"); console.log(newStr); // logs "foo_test_bar_test_" 

Comments

1

Try this:

mystring.replace(/\{5\}/g,'replaced'); 

You need to escape the curly brackets\{ and \}.

DEMO

http://jsfiddle.net/tuga/Gnsq3/

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.