If you use str. replace ("-","! ") Will only Replace the first matched character.
Str. replace (/\-/g ,"! "), You can replace all matched 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
Occurrence 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
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 pointsalert (s );
Yields this result: "Hello! Regexps are fun !"
You can use the following methods .:
String. replace (/reallyDo/g, replaceWith );
String. replace (new RegExp (reallyDo, 'G'), replaceWith );
String:The string expression contains the substring to be replaced.
ReallyDo:The substring to be searched.
ReplaceWith:The substring used for replacement.
Copy codeThe Code is as follows:
<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>