Aqil
Aqil

Reputation: 114

How to make replace() global in JavaScript

I know this question had been asked lot of time but i could not find solution. I have some smilies which each of them has code to be rendered as smiley using replace() , but I get syntax error, I don't know why and how to render my code :/ to smiley

txt = " Hi :/ ";
txt.replace("/\:/\/g","<img src='img/smiley.gif'>");

Upvotes: 3

Views: 2590

Answers (2)

Sunny Patel
Sunny Patel

Reputation: 8078

Your regular expression doesn't need to be in quotes. You should escape the correct / forward slash (you were escaping the wrong slash) and assign the replacement, since .replace doesn't modify the original string.

txt = " Hi :/ ";
txt = txt.replace(/:\//g,"<img src='img/smiley.gif'>");

Based on jonatjano's brilliant deduction, I think you should add a little more to the regular expression to avoid such calamities as interfering with URLs.

txt = txt.replace(/:\/(?!/)/g,"<img src='img/smiley.gif'>");

The above ensures that :// is not matched by doing a negative-lookahead.

Upvotes: 9

axiac
axiac

Reputation: 72177

There are two problems in the first argument of replace() it escapes the wrong characters and it uses a string that seems to contain a regex instead of a real RegExp.

The second line should read:

txt.replace(/:\//g,"<img src='img/smiley.gif'>");

/:\//g is the regex. The first and the last / are the RegExp delimiters, g is the "global" RegExp option (String.replace() needs a RegExp instead of a string to do a global replace).

The content of the regex is :/ (the string you want to find) but because / has a special meaning in a RegExp (see above), it needs to be escaped and it becomes :\/.

Upvotes: 2

Related Questions