The first time I discovered that if the replace() method in JavaScript is directly used to use str.replace("-","!") will only replace the first matching character.
str.replace(//-/g,"!") can all replace the matching characters (g is the global flag).
replace()
The replace() method returns the string that results when you replace text matching its first argument
(a regular expression) with the text of the second argument (a string).
If the g (global) flag is not set in the regular expression declaration, this method replaces only the first
occur of the pattern. For example,
var s = "Hello. Regexps are fun." ;s = s.replace(//./, "!" ); // replace first period with an exclamation pointalert(s);
produces the string “Hello! Regexps are fun.” Including the g flag will cause the interpreter to
perform a global replace, finding and replacing every matching substring. For example,
var s = "Hello. Regexps are fun." ;s = s.replace(//./g, "!" ); // replace all periods with exclamation pointtsalert(s);
yields this result: “Hello! Regexps are fun!”
So the following methods can be used:
string.replace(/reallyDo/g, replaceWith);
string.replace(new RegExp(reallyDo, 'g'), replaceWith);
string: A string expression contains the substring to replace.
reallyDo: The searched substring.
replaceWith: Substring used for replacement.
Js code
<script type="text/javascript"> String.prototype.replaceAll = function(reallyDo, replaceWith, ignoreCase) { if (!RegExp.prototype.isPrototypeOf(reallyDo)) { return this.replace(new RegExp(reallyDo, (ignoreCase ? "gi": "g")), replaceWith); } else { return this.replace(reallyDo, replaceWith); } } </script>The above article JS replacement string all the specified characters (implementation code) are all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.