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?

Lee Taylor
  • 7,761
  • 16
  • 33
  • 49
Gatekeeper
  • 1,586
  • 3
  • 21
  • 33

3 Answers3

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.

Community
  • 1
  • 1
Brendan
  • 1,853
  • 11
  • 18
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_"
willwclo
  • 96
  • 1
  • 3
1

Try this:

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

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

DEMO

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

Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268