Javascript string replace all

In PHP, str_replace will replace all the occurrence key in a string to the value that specified by user.
In Javascript, if you using a replace function without specified, it will only replace the first occurrence of the key in the string to the value.

For example :

<script>
var js_str = "Visit RedHat now & RedHat will give out free gift to you";
js_str.replace("RedHat","how2guru");
alert(js_str);
</script>

The output of the above script will give you :
Visit how2guru now & RedHat will give out free gift to you 
 
If you would like to replace all the occurrence key to the value, you have to use the global match. It will replace all the occurrence key.

For example : 

<script>
var js_str = "Visit RedHat now & RedHat will give out free gift to you";
js_str.replace(/RedHat/g,"how2guru");
alert(js_str);
</script>

The output of the above script will give you :
Visit how2guru now & how2guru will give out free gift to you

3 Comments to “Javascript string replace all”

  1. [...] With thanks to Joey for the basics behind this post and how2guru for the every occurence [...]

  2. Fred 10 July 2009 at 10:52 pm #

    Hi h2g,

    Thanks for that fix, it occurred to me that my fix for removing all comma’s was only removing the first.

    I’ve done a small blog about it.

    Cheers.

    http://defaultyes.com/javascript-how-to-edit-the-end-of-a-string

  3. Aayushi 26 August 2009 at 3:23 pm #

    Hey.. Very helpful..

    Thanks a lot.


Leave a Reply