JS strings have replace() method. But this method will only replace the first string that matches. As shown in the following example:
<HTML><HEAD><TITLE> New Document </TITLE></HEAD><BODY><script>var str = "wordwordwordword";var strNew = str.replace("word","Excel");alert(strNew);</script></BODY></HTML>If you want to replace all of them, JS does not provide a method like replaceAll. Use regularity to achieve the effect of Replace:
str.replace(/word/g,"Excel")g means: perform global matches (find all matches instead of stopping after finding the first match).
<HEAD><TITLE> New Document </TITLE><script>function replaceAll(str){if(str!=null)str = str.replace(/word/g,"Excel")return str;}</script></HEAD><BODY><script>var str = "wordwordwordword";var strNew = str.replace("word","Excel");strNew = replaceAll(str);alert(strNew);</script></BODY></HTML>There is a similar way to write the above:
str.replace(new RegExp("word","gm"),"Excel")g performs a global match (find all matches instead of stopping after the first match is found).
m Perform multi-line matching.
In addition, you can also add prototype methods of Stirng objects:
String.prototype.replaceAll = function(s1,s2){ return this.replace(new RegExp(s1,"gm"),s2); }This way you can use replaceAll just like using replace method
str.replaceAll("word","Excel");To summarize, three ways
1. str.replace(/oldString/g,newString)
2. str.replace(new RegExp(oldString,"gm"),newString)
3. Add String object prototype method replaceAll