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”
Leave a Reply
[…] With thanks to Joey for the basics behind this post and how2guru for the every occurence […]
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
Hey.. Very helpful..
Thanks a lot.