The JS string has the Replace () method. However, this method replaces only the first string that is matched to. The following example:
<HTML><HEAD><TITLE> New Document </TITLE></HEAD><BODY><script> var"wordwordwordword"; var strnew = str.replace ("word","Excel" ); alert (strnew); </script></BODY></HTML>
If you want to replace all, JS does not provide replaceall such a method. Use regular tables to achieve the effect of replace:
Str.replace (/word/g,"Excel")
the meaning of G is to perform a global match (find all matches rather than stop after the first match is found).
<HEAD><TITLE> New Document </TITLE><script>function ReplaceAll (str) {if(str!=NULL) Str= Str.replace (/word/g,"Excel") returnstr;}</script></HEAD><BODY><script>varstr ="Wordwordwordword"; varStrnew = Str.replace ("Word","Excel"); Strnew=ReplaceAll (str); alert (strnew);</script></BODY></HTML>
There is a similar wording in the above:
Str.replace (new RegExp ("word","GM")," Excel ")
G performs a global match (finds all matches rather than stops after the first match is found).
M performs multi-line matching.
In addition, you can also add a prototype method for the Stirng object:
String.prototype.replaceAll = function (s1,s2) { returnthis. replace (new RegExp (S1,"GM"), S2);
This allows you to use ReplaceAll as you would with the Replace method.
Str.replaceall ("word","Excel");
Sum up, three ways
1. Str.replace (/oldstring/g,newstring)
2. Str.replace (New RegExp (oldstring, "GM"), newstring)
3. Adding a String object prototype method ReplaceAll