JS implementation of replaceAll method of of instance code

  • 2020-03-29 23:42:33
  • OfStack

First time to find the replace() method in JavaScript if you use STR. Replace ("-","!") ) replaces only the first matched character.
And STR. Replace (/ \ - / g, "!" ) can replace all matched characters (g is the global flag).

The 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.r eplace (/ \. /, "!" ); / / replace first period with the an the 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.r eplace (/ \. J/g, "!" ); / / replace all periods with the exclamation pointsalert (s);

Yields this result: "Hello! Regexps are fun!"

So you can use the following ways.
String. The replace (/ reallyDo/g, replaceWith);
String. The replace (new RegExp (reallyDo, 'g'), replaceWith);

String: The string expression contains the substring to be replaced.
ReallyDo: The searched substring.
ReplaceWith: Substring used for substitution.

<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);  

Related articles: