In many projects, we often need to use JS, in front of the front page to do some of the elements to make changes, JS replace () method is essential.
Frequent use of "abcabcabc". Replace ("A", "B") students should be more clear, the final result of the change statement is BBCABC, this method can only replace
The first matching element. If you replace all of them. You can use regular expressions to:
"Abcabcabc". Replace (/a/g, "B").
So if you want to replace a, you can also replace a.
Then you can use "ABCABCABC". Replace (/a/ig, "B");
FLAG:I identification Ignore ignore size, G identity Global repeatedly retrieved, m ID multiple-line search (this is not tested for a while)
You can also use their combinations, such as the IG used above to replace all the IDs and ignore the case.
Formal regular formulation:
var reg=new RegExp (/patten/flag)
var strs= "". Match (REG);
When Flag uses G, STRs returns an array of strings.
If you want any of the multiple strings to match, you can use the
Reg=new RegExp (/abc|xyz/ig);
Replace method in JavaScript (replace ReplaceAll effect All)
The replace () method in JavaScript if used directly with Str.replace ("-", "!") Only the first matching character will be replaced.
and Str.replace (/\-/g, "!") You can replace all the matching characters (G is the global flag).
Str.replace (/\ '-'/g, "!") ' -' is the character you want to be replaced.
JS code function iestr2ascii (str) {var re =/%/g; str = str.replace (Re, "%25"); var re =/=/g; str = str.replace (Re, "%3d"); re =/\?/g; str = str.replace (Re, "%3f"); Re =/\ '/g; str = str.replace (Re, "%27"); Re =/&/g; str = str.replace (Re, "%26"); return str; }
Instance:
JS code function encodeurl (str) { return encodeuri (str). Replace (/=/g, "%3d"). Replace (/\+/g, "%2b"). Replace (/\?/g, "%3f"). Replace (/\&/g, "%26"); } Function htmlencode (str) { return Str.replace (/&/g, "&"). Replace (/\ "/g", """). Replace (/</g, "<"). Replace (/>/g, ">"). Replace (/ /g, " "); } function htmldecode (str) { Return str.replace (/\"/g, "\"). Replace (/\</g, "<"). Replace (/\>/g, ">"). Replace (/\ /g, " "). Replace (/\&/g, "&"); }