This article gives a detailed summary of how to implement replaceAll in JavaScript. If you need it, you can refer to it and hope to help you find replace () in JavaScript for the first time () if you directly 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.
The Code is as follows: