RSS
people

Javascript string replace all

Share/Save/Bookmark

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 Responses to “Javascript string replace all”

  1. DefaultYes | The online ramblings of one man » JavaScript: How To Edit the End of a String Says:

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

  2. Fred Says:

    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 Says:

    Hey.. Very helpful..

    Thanks a lot.

Leave a Reply