Gatekeeper
Gatekeeper

Reputation: 1616

Replace text containing number in js

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?

Upvotes: 1

Views: 243

Answers (3)

Brendan
Brendan

Reputation: 1873

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.

Upvotes: 3

willwclo
willwclo

Reputation: 96

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_"

Upvotes: 2

Pedro Lobito
Pedro Lobito

Reputation: 99071

Try this:

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

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

DEMO

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

Upvotes: 1

Related Questions