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
- » Javascript select a div content
- » Dynamic wizard form using dhtml & javascript.
- » Detect & trigger action while user exit webpage
















July 10th, 2009 at 10:45 pm
[...] With thanks to Joey for the basics behind this post and how2guru for the every occurence [...]
July 10th, 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
August 26th, 2009 at 3:23 pm
Hey.. Very helpful..
Thanks a lot.