Javascript Replace Function


I just have been asked, “Does, Javacript string.replace function replace string only once?”. I said, “No”. But when I test the function I was wrong. Then did a search on internet and found that Javascript’s Replace function is not a String Replacement function as in anyother language, but it is regular experssion based Replacement function. Once it read this, I am sure why I am wrong, and here is what you need to do in term of using String.Replace function to work as Replace function (for string) to replace every instanace.

 Simply change your JS line as

var str =’this is string in which I will replace is with ab’;
str = str.replace(‘is’,’ab’);

To this one…

var str =’this is string in which I will replace is with ab’;
str = str.replace(/is/g,’ab’);

And you get a new string where all “is” got replaced with “ab”.  /is/g  is a regular expression syntax where  “is” is a string literal  we are going to replace and “g” signify that it will be replaced globally.

Hope it will help you in your search and replace :).

,