Thanks to the regular expression provided by the waves. For the original post, see:
Http://www.iecn.net/bbs/view/106503.html
Because you want to replace a template, the variables in the template are named in the format of $ {MyName. When performing global replacement, there are two difficulties:
1. You cannot replace special symbols such as $.
2. Either case sensitivity cannot be ignored
With the help of the waves, we finally achieved the best implementation method :)
Best Practice:Copy codeThe Code is as follows: <script type = "text/javascript">
String. prototype. replaceAll = stringReplaceAll;
Function stringReplaceAll (AFindText, ARepText ){
Var raRegExp = new RegExp (AFindText. replace (/([\ (\) \ [\] \ {\} \ ^ \ $ \ + \-\*\? \. \ "\ '\ | \/\])/G," \ $1 ")," ig ");
Return this. replace (raRegExp, ARepText );
}
Var ssString = "www.cnlei.com; www.CnLei.net; www.cnlei.org ";
Alert (ssString. replaceAll ("cnlei", "iecn "));
SsString = "www. $ {MyName}. com; www. $ {MyName}. net; www. $ {MyName}. org ";
Alert (ssString. replaceAll ("$ {MyName}", "cnlei "));
SsString = "www. {MyName}. com; www. {MyName}. net; www. {MyName}. org ";
Alert (ssString. replaceAll ("{MyName}", "cnlei "));
</Script>
Previous use Method 1: (ignore size can be implemented, but replacement of special symbols cannot be implemented)Copy codeThe Code is as follows: <script type = "text/javascript">
String. prototype. replaceString = stringReplaceAll;
Function stringReplaceAll (AFindText, ARepText ){
Var raRegExp = new RegExp (AFindText, "ig ");
Return this. replace (raRegExp, ARepText );
}
Var ssString = "www.cnlei.com; www.CnLei.net; www.cnlei.org ";
Alert (ssString. replaceString ("cnlei", "iecn "));
SsString = "www. $ {MyName}. com; www. $ {MyName}. net; www. $ {MyName}. org ";
Alert (ssString. replaceString ("$ {MyName}", "cnlei "));
SsString = "www. {MyName}. com; www. {MyName}. net; www. {MyName}. org ";
Alert (ssString. replaceString ("{MyName}", "cnlei "));
</Script>
Method 2 previously used: (special symbols such as $ can be replaced, but case sensitivity cannot be ignored)Copy codeThe Code is as follows: <script type = "text/javascript">
String. prototype. replaceString = function (s1, s2 ){
This. str = this;
If (s1.length = 0) return this. str;
Var idx = this. str. indexOf (s1 );
While (idx> = 0 ){
This. str = this. str. substring (0, idx) + s2 + this. str. substr (idx + s1.length );
Idx = this. str. indexOf (s1 );
}
Return this. str;
}
Var ssString = "www.cnlei.com; www.CnLei.net; www.cnlei.org ";
Alert (ssString. replaceString ("cnlei", "iecn "));
SsString = "www. $ {MyName}. com; www. $ {MyName}. net; www. $ {MyName}. org ";
Alert (ssString. replaceString ("$ {MyName}", "cnlei "));
SsString = "www. {MyName}. com; www. {MyName}. net; www. {MyName}. org ";
Alert (ssString. replaceString ("{MyName}", "cnlei "));
</Script>