0

I'm trying to replace multiple occurrences of a string and nothing seems to be working for me. In my browser or even when testing online. Where am I going wrong?

str = '[{name}] is happy today as data-name="[{name}]" won the match today. [{name}] made 100 runs.';

str = str.replace('/[{name}]/gi','John');

console.log(str);

http://jsfiddle.net/SXTd4/

I got that example from here, and that too wont work.

4 Answers 4

2

You must not quote regexes, the correct notation would be:

str = str.replace(/\[{name}\]/gi,'John');

Also, you have to escape the [], because otherwise the content inside is treated as character class.

Updating your fiddle accordingly makes it work.

There are two ways declaring regexes:

// literal notation - the preferred option
var re = /regex here/;
// via constructor
var re = new Regexp('regex here');
Sign up to request clarification or add additional context in comments.

Comments

1

You should not put your regex in quotes and you need to escape []

Simply use

str = str.replace(/\[{name}\]/gi,'John');

DEMO

Comments

1

While there are plenty of regex answers here is another way:

str = str.split('[{name}]').join('John');

1 Comment

Interestingly, this is faster in the new chromes: jsperf.com/regex-vs-split-join
0

The characters [ ] { } should be escaped in your regular expression.

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.