Detailed JS regular replace use method

  • 2021-01-22 04:52:07
  • OfStack

Before moving on to the more advanced applications of replace, let's briefly review some of the most important aspects of JS regular expressions to help you get to the basics. Then we'll cover the use of JS regular expressions in replace and some classic examples.

1. Regular expression creation

JS regulars are created in two ways: new RegExp() and direct literals.


// use RegExp Object creation 
var regObj = new RegExp("(^\s+)|(\s+$)","g");

// Created using direct literals 
var regStr = /(^\s+)|(\s+$)/g;

Where, g means full-text match, and i and m are related to it. i means that case is ignored when matching, m means multi-line match, and if multiple conditions are used at the same time, it is written as: gmi

2. (), [], {}

() is used to extract the matching string. The number of () in the expression will result in the number of matching strings. For example, (\s+) represents a string of contiguous Spaces.

[] is the range of characters to define a match. For example, [a-zA-Z0-9] means that the character text should match English characters and numbers.

\d{3} matches 3 Spaces, \d[1,3] matches 1~3 Spaces.

3. ^ and $

^ matches the beginning of a string, for example (^a) matches a string beginning with the letter a

$matches the end of a string. For example, (b$) matches a string ending in the letter b

^ Another 1 function is to negate, such as [^xyz] to indicate that the matching string does not contain xyz

It is important to note that if the ^ appears in [], it is usually the inverse, and if it appears elsewhere, it is the beginning of the matching string

4. \d \s \w .

\d matches 1 non-negative integer, equivalent to [0-9]

\s matches 1 whitespace character

\w matches 1 English letter or number, equivalent to [0-9a-zA-Z]

. Matches any character except a newline character, equivalent to [^\n]

5. * + ?

* matches the previous element 0 or more times, for example (\s*) matches 0 or more Spaces

+ matches the previous element one or more times, such as (\d+), which matches a string consisting of at least one integer

The & # 63; Matches the previous element 0 or 1 times, equivalent to {0,1}, for example (\w?) Matches a string consisting of at most one letter or number

6. test, match

This is mostly the syntax for JS regular expressions, but test is used to check if a string matches a regular expression, and returns true if it does, or false if it does


/\d+/.test("123") ; //true

/\d+/.test("abc") ; //false

ES94en is the result of retrieving a regular match and returning it as an array

"186a619b28".match(/\d+/g); // ["186","619","28"]

The above is basically the basic knowledge that I often use, not very comprehensive, not commonly used is not listed, because the list is only decoration, but confuse the primary and secondary!

7. replace

replace is itself a method on an JavaScript string object that allows two arguments:

replace([RegExp|String],[String|Function])
The first argument can be either a plain string or a regular expression

The second argument can be either a plain string or a callback function

If the first argument is RegExp, JS will first extract the matched result from RegExp, and then replace the matched result with the second argument, one by one

If the second argument is a callback function, it will be called back once for every match. Each callback will pass the following arguments:


result:  The result of this match 

$1,...$9:  There are several in regular expressions () , will pass a couple of parameters, $1~$9 Represents each of the matches in this match () Extract the results, the most 9 a 

offset: Record the starting position of the match 

source: Accepts the matching original string 

Here are some classic examples of replace and JS regular collocations:

(1) Implement the string trim function, remove the space on both sides of the string


String.prototype.trim = function(){

  // way 1 : will match to each 1 I'm going to use both of them "" replace 
  return this.replace(/(^\s+)|(\s+$)/g,function(){
    return "";
  });

  // way 2 : and the way 1 It's the same principle 
  return this.replace(/(^\s+)|(\s+$)/g,'');
};

^ \ s + white space characters in a row, starting with a space \ s + $said with a space at the end of the white space characters in a row, add () is the outcome of matches to extract, due to the relationship between |, so the expression will match to the two result sets, and then execute two replacement:


String.prototype.trim = function(){
  /**
   * @param rs : Matching result 
   * @param $1: The first 1 a () The extraction results 
   * @param $2: The first 2 a () The extraction results 
   * @param offset: Match start position 
   * @param source : Raw string 
   */
  this.replace(/(^\s+)|(\s+$)/g,function(rs,$1,$2,offset,source){
    //arguments Each element in the 1 A parameter 
    console.log(arguments);
  });
};

" abcd ".trim();

 Output results: 

[" ", " ", undefined, 0, " abcd "] // The first 1 Secondary match result 
[" ", undefined, " ", 5, " abcd "] // The first 2 Secondary match result 


(2) Extract parameter name and parameter value from browser url, and generate 1 object of key/value


function getUrlParamObj(){
  var obj = {};
  // To obtain url The parameter part of 
  var params = window.location.search.substr(1);
  //[^&=]+  Said do not contain & or = Of the contiguous character, plus () Extract the corresponding string 
  params.replace(/([^&=]+)=([^&=]*)/gi,function(rs,$1,$2){
    obj[$1] = $2;
  });

  return obj;
}

/([^ & =]+)=([^ & =]*)/gi =

/value (xxxx=xxx). Each time one of these results is matched, the callback is executed, and the matching key and value are passed, corresponding to $1 and $2

(3) Insert a new string at the specified position in the string


String.prototype.insetAt = function(str,offset){

  // use RegExp() The constructor creates the regular expression 
  var regx = new RegExp("(.{"+offset+"})");

  return this.replace(regx,"$1"+str);
};

"abcd".insetAt('xyz',2); // in b and c Inserted between xyz
>> "abxyzcd"

When offset=2, the regular expression is: (^.{2}). Any character other than \n, followed by {2} matches the first two consecutive characters consisting of numbers or letters, adding () will extract the matched result, and then replace the matched result with a new string using replace, such as: result = result +str

(4) Convert the phone number 12988886666 to 12988886666


function telFormat(tel){

  tel = String(tel);

  // way 1
  return tel.replace(/(\d{3})(\d{4})(\d{4})/,function (rs,$1,$2,$3){
    return $1+" "+$2+" "+$3
  });

  // way 2
  return tel.replace(/(\d{3})(\d{4})(\d{4})/,"$1 $2 $3");
}

(\d{3}\d{4}\d{4}) can match the full phone number and extract the first 3, 4-7 and 8-11 bits respectively. "$1 $2 $3" is to add space between the 3 result sets to form a new string and then replace the full phone number.

(5) Implement the function escapeHtml, which will < , > , & , "to escape


function escapeHtml(str) {
  // matching < > " &
  return str.replace(/[<>"&]/g, function(rs) {
    switch (rs) {
      case "<":
        return "&lt;";
      case ">":
        return "&gt;";
      case "&":
        return "&amp;";
      case "\"":
        return "&quot;";
    }
  });
}

The above is all the content of this article, I hope to help you learn.


Related articles: