Regular expression describes a pattern of string matching. It is commonly used in methods to represent specific content with special symbols. Search, replace and extract information in a string. Regular expressions in JS are represented by RegExp objects.

Define regular expressions

Literal creation/regular expressions /[modifiers writable or not writable]

New RegExp(string, [modifier])

let reg = /\d+/g;
reg = new RegExp("\\d+"."g");
Copy the code

The difference is that literal-defined regulars cannot be concatenated with strings. Instances can be concatenated with strings. Part of the contents of regular expressions are values stored in variables. If the re contains a variable value, you can’t use literal creation because both slashes are metacharacters. Instead, use the constructor, because it passes rules like strings, which can be concatenated.

        let str = "davina";
        reg = /^@"+str+"@$/;
        console.log(reg.test("@davina@")); //false
        console.log(reg.test('@"""strrrrr"@')); //true

        reg1 = new RegExp("^ @" + str + "@ $");
        console.log(reg1.test("@davina@")); //true
Copy the code

Modifier (can be multiple after the second slash)

  • I: Case insensitive, ignoring case when determining a match

  • M: Multi-line mode. When the end of a line of text is reached, the search continues to see if there is an item matching the pattern in the next line

  • G: for global matching, the pattern is applied to all strings and does not stop when the first match is found

Common re characters

1. Metacharacters (common)

expression meaning
\d Numbers (any number between 0 and 9)
\D Any character other than a number
\w Numbers, letters, underscores ([0-9 a-z a-z])
\W Non-numbers, letters, underscores
\s The blank space
\S The space
\ \ The backslash
\ ‘ Single quotes
. Any character (representing all)
\. The real point
\n A newline
// metacharacter: ^ which character begins $which character ends
console.log(/^\d+$/.test('2021my')); //false

//. Not a decimal point, but based on any character outside \n can be escaped with \
console.log($/ / ^ 2 \. 3.test('2.3')); //true

/ / x | y: characters of x or y, it usually priority problems and can use parentheses to group
console.log(18 | $29 / / ^.test('182')); //true
console.log($/ / ^ 18 | (29).test('182')); //false
Copy the code

2. Brackets

expression meaning
[abc] Find any character in parentheses
[^abc] Find any character that is not between the brackets
[0-9] Find any number from 0 to 9
[a-z] Find characters from small A to small Z
[A-Z] Find characters from big A to big Z
[\u4e00-\u9fa5] Chinese interval
// [] is used to represent its own meaning. It does not contain multiple digits
let reg2 = $/ / ^ [10-29];  //=> represents 1 or 0 or 2 or 9
console.log(reg2.test("1"));//=>true
console.log(reg2.test("9"));//=>true
console.log(reg2.test("0"));//=>true
console.log(reg2.test("Seven"));//=>false
console.log(reg2.test("10"));//=>false 
Copy the code

3, quantifiers

expression meaning
* Repeat at least 0 times and at most {0,}(0 to more)
+ Repeat at least 1 time and at most {1,}(1 to more)
? Repeat at least 0 and at most 1 {0,1}(0,1 is possible)
{n} Repeat n times (exactly)
{n,m} Repeat n to m times (at least n, at most M)
{n,} At least repeat n, at most (n to many)
n$ Matches any string ending in n
^n Matches any string that begins with n
x|y Match x or y

4, grouping

expression meaning
{} grouping

The single item assembled into the expression, so that can be treated as an independent unit with a |, *, +, or that way? And so on to process the items in the cell

let str = "130828199012040112";
let reg = /^(\d{6})(\d{4})(\d{2})(\d{2})\d{2}(\d)(? :\d|X)$/;
console.log(reg.exec(str)); / / / "130828199012040112", "130828", "1990", "12", "04", "1"]
Copy the code

If you want to capture the number and also want to capture the number separately, you can use the following method:

    let str = "{2021} {11} day {11}",
        reg = /\{(\d+)\}/g,
        All_ary = [],
        Single_ary = [];
    res = reg.exec(str);
    while (res) {
        let [All, Single] = res;
        All_ary.push(All);
        Single_ary.push(Single);
        res = reg.exec(str);
    }
    console.log(All_ary, Single_ary); / / / {2021}, {11} ", "{11}]" (3) (" 2020 ", "11", "11"]
Copy the code

Third, the regular method

1. RegExp object related methods

  • test()
    • Function: Checks whether the regular expression matches the specified string. It is classified to the search() method in the string, except that test returns a Boolean and search returns 1/-1.
    • Syntax: rege.test (string);
    • Return value: Returns true/false
let str = 'hello world';
console.log(/^hello$/.test(str)); //true
Copy the code
  • exec()
    • Performs a search match in a specified string. Similar to match. But it can iterate through multiple matches in a single string and match will only return matches
    • Syntax: rege.exec (string)
    • Return value: array or NULL
let reg = /ab*/g;
let str = 'tttadfdfjaddadabbtrttw';
console.log(reg.exec(str));//["a", index: 3, input: "tttadfdfjaddadabbtrttw", groups: undefined]

Copy the code

2, String object related methods

  • match()
    • Matches the specified string or re, and puts the matched result into an array
    • Syntax: string.match (string or re)
    • Return value: put the result in the array and return, null if not found
    • Note: Without the G modifier, only one result is matched and two attributes are added to the found array: index(find the position of the character) and input(find the original string from which string).
    • The differences between exec() and match() are as follows: 1. One is the re method and the other is the String method, and exec() will only match the first matching String (g does not apply to it). Match returns all matched arrays depending on whether g is in the re.
    let str = 'avada33fkdja123fas22gj34qw3r';
    let reg1 = /\d+/g;
    console.log(reg1.exec(str)[0]); / / 33
    console.log(str.match(reg1)); //["33", "123", "22", "34", "3"]

Copy the code
  • search()
    • Function: Finds the position where the matching string first appears
    • Syntax: string.search (string or re)
    • Return value: index of return location found, -1 not found
    • Note: The search() method argument can be regular, and the indexOf() method argument cannot be regular
    let str = 'davina123Davian';
    let re = /\d/;
    console.log(str.indexOf(re), str.search(re));/ / - 1 6
Copy the code
  • split()
    • Split into arrays according to convention strings or string rules and accept a string or re
    • Syntax: string. Split (string or re)
    • Return value: array
    let color = '1 red green 2';
    console.log(color.split(' ')); //["1", "red", "green", "2"]
    console.log(color.split((/\s/), 3)) //["1", "red", "green"]
Copy the code
  • The replace () method
    • Function: Replaces a matching string
    • Grammar: STR. Replace (regexp | substr, newSubStr | function)
    • Argument: regexp This is a re or literal that is replaced by the return value of the second argument. Substr: a string to be replaced by newSubStr, with only the first match being replaced; NewSubStr replaces the character that matches the first argument in the original string. Function The function used to create a new substring whose return value replaces the result of the first argument.
    • Return value: new string after replacement, no change to the original string. It is important to note that this function must return a value, otherwise undefined will be used instead
    // Replace with a literal
    let str = ' apple apple APPLE ';
    let r1 = str.replace('a'.'A');
    console.log(r1); // Apple Apple Apple replaces only the first matching character

    let r2 = str.replace(/a/gi.'Aa');
    console.log(r2); // Aapple Aapple Aapple can be completely replaced with re, and the following argument can be a string

    // Swap two monotonous positions in a string
    let reg2 = /(\w+)\s(\w+)/;
    let str1 = 'tom mark';
    console.log(str1.replace(reg2, 'the $2, $1')); //mark,tom
Copy the code

Four, capture

Regular capture is greedy and lazy. Cupidity is when the re tries to capture as many things as possible at a time. Lazy means that the re will not be captured after a successful capture, regardless of whether the following string meets the criteria. By default, regular matches are greedy matches. If you want to cancel them, you just set them after the quantifier metacharacter. You can.

For laziness, this feature is used in the exec() method. The result it captures is null or an array. Every exec() is executed, only one result can be captured in accordance with the regular rule. When we execute 100 times, the result we get is always the first matched result, which is caused by the laziness of the regular capture, the default is to capture the first one. The reason for laziness is that by default the value of lastIndex(the starting index of the current re’s next match) is not changed. It is looked up from the beginning of the string each time, so only the first one is always found. We can solve this problem with the global modifier G. After the global match modifier g is set,lastIndex will change itself after the first match. When all matches are completed, the result of the second capture will be null,lastIndex will return to the original value, and the second capture will start from the first.

    let str = "lily2019lily2020";
    let reg = /\d+/
    let reg1 = /\d+? /g;

    console.log(str.match(reg)); //["2019", index: 4, input: "lily2019lily2020", groups: undefined]
    console.log(str.match(reg1)); //["2", "0", "1", "9", "2", "0", "2", "0"]
Copy the code

Five, common re

Capitalize the first letter of each word


    let str = "keep on going never give up.";
    let reg = /\b([a-zA-Z])[a-zA-Z]*\b/g;
    
    str = str.replace(reg, (. arg) = > {
        let [content, $1] = arg;
        $1 = $1.toUpperCase();
        content = content.substring(1);
        return $1 + content;
    });
    console.log(str); //Keep On Going Never Give Up.
Copy the code

Verifies whether it is a significant number

// +/- may occur may not occur; The first digit is not 0 if the number of digits ranges from 0 to 9. Decimals are optional. Once you have a decimal point, you have to have a number behind it
let reg = / ^ +] [-? (\d|([1-9]\d+))(\.\d?) $/;
Copy the code

Thousands-url handles $time string formatting

~ (function () {
        / / 1. Micrometer
        * @params: * @return * [string] String after the thousandMark */
        function thousandMark() {
            return this.replace(/ \ d {1, 3} (? =(\d{3})+$)/g.(content) = > content + ",");
        }


        / / 2. The url of the processing
        * @params * @return * [object] Stores all question mark parameters as key-value pairs and returns */
        function queryURLParams() {
            let obj = {},
                reg = /([^?=&#]+)=([^?=&#]+)/g;
            this.replace(reg, (. [, $1, $2]) = > (obj[$1] = $2));
            this.replace(/#([^?=&#]+)/g.(. [, $1]) = > (obj["hash"] = $1));
            return obj;
        }

        //3. Time string formatting processing
        @params * templete:[string] The last template we want to get for the date format */
        function formatTime(templete = "{0} year {1} month {2} day {3} {4} minutes {5} seconds") {
            let timeAry = this.match(/\d+/g);
            return templete.replace(/\{(\d+)}/g.(. [, $1]) = > {
                let time = timeAry[$1] | |"00";
                return time.length < 2 ? "0" + time : time;
            });
        }

        /* Extend all methods to the built-in string.prototype class */
        ["thousandMark"."queryURLParams"."formatTime"].forEach((item) = > {
            String.prototype[item] = eval(item); }); }) ();// Verify
    let num = "1234553423423"; / / 1234553423423
    console.log(num.thousandMark());

    let url = "http://www.davina.cn/?lx=1&from=qq#video";
    console.log(url.queryURLParams()); //{lx: "1", from: "qq", hash: "video"}

    let time = "The 2020-8-13 16:1:39";
    console.log(time.formatTime()); // 16:01:39 on 13 August 2020

Copy the code