grammar

str.replace(regexp|substr, newSubStr|function)

Parameter description:

  1. regexp (pattern)

A RegExp object or its literal. What the re matches is replaced by the return value of the second argument.

  1. substr (pattern)

A string to be replaced by newSubStr. It is treated as an entire string, not as a regular expression. Only the first match is replaced.

  1. newSubStr (replacement)

A string used to replace the matching part of the first argument in the original string. Special variable names can be interpolated into the string. See using strings as arguments below.

  1. function (replacement)

A function that creates a new substring whose return value replaces the result of the first argument. Refer to specifying a function as an argument below.

Return value: Returns a new string that partially or completely matches the replacement pattern.

Description: This method does not change the string from which it was called, but simply returns a new, replaced string. When performing global search and replace, the regular expression must contain the G flag.

Use a string as an argument

Substitution strings can insert the following special variable names:

The variable name On behalf of the value of the
$$ Insert a “$”.
$& Insert the matching substring.
$` Inserts the content to the left of the currently matched substring.
$’ Inserts the content to the right of the currently matched substring.
$n If the first argument is a RegExp object and n is a non-negative integer less than 100, insert the NTH parenthes-matching string. Tip: The index starts at 1. If no NTH grouping exists, the matches are replaced with literals. If there is no third grouping, the match is replaced with “$3”.
$ Here Name is a group Name. If there is no grouping (or match) in the regular expression, the variable is treated as an empty string. Only available in browsers that support named group capture.

Specify a function as an argument

You can specify a function as the second argument. In this case, the function is executed when the match is executed. Function returns the value as the replacement string. (Note: The special substitution argument mentioned above cannot be used here.) Also note that if the first argument is a regular expression and it is a global match pattern, the method will be called multiple times, with each match being called.

The variable name On behalf of the value of the
match Matching substring. (Corresponding to the $& above.)
p1,p2, … If the first argument to the replace() method is a RegExp object, it represents the NTH parenthes-matched string. (Corresponding to the above
1 . 1,
2, etc.) For example, if /(\a+)(\b+)/ is used to match, p1 is \a+ and p2 is \b+.
offset Offset of the matched substring within the original string. (For example, if the original string is ‘abcd’ and the matched substring is’ BC ‘, this parameter will be 1.)
string The original string to be matched.
NamedCaptureGroup Name the object that the capture group matches

The instance

Example 1 simple string substitution:

    let reg = /sentence/;
    let str = 'This is a simple centence.';
    str = str.replace('centence'.'sentence'); // Plain string substitution
    console.log(str); // This is a simple sentence.
    
    str = str.replace(reg, 'example');
    console.log(str); // This is a simple example.
Copy the code

Example 2 The code provided in this example ensures that the matching string uppercase characters are correct:

    let text = "javascript Tutorial";
    let txt = text.replace(/javascript/i."JavaScript");
    console.log(txt); // Javascript Tutorial
Copy the code

Example 3 In this example, we will convert “Doe, John” to the form “John Doe” :

    let n = "Doe , John";
    let nn = n.replace(/(\w+)\s*,\s*(\w+)/."$2 $1");
    console.log(nn); // John Doe
Copy the code

Example 4 All double quotes replace single numbers:

    let e = '"aa", "ab" , "bb"';
    let ee = e.replace(/"([^"]*)"/g."' $1 '");
    console.log(ee); // 'aa', 'ab', 'bb'
Copy the code

Example 5 using a string as an argument:

    var st = 'abcdefg';
    var reg1 = /(c)de/g;
    st = st.replace(reg1, '$$d'); // The c wrapped in parentheses is replaced by $, and then the entire matching CDE is replaced
    console.log(st); // ab$dfg
Copy the code

Example 6 You can perform the following operations to capitalize the first letter of a word in a string

Method 1:

    let str = 'hello world 000 ___',
        reg = /(\w)(\w*)/g;
    let res = str.replace(reg, function (match, p1, p2, offset, str) {
        console.log('match:', match, 'p1:', p1, 'p2:', p2, 'offset:', offset, 'str:', str);
        return p1.toUpperCase() + p2;
    });
    console.log('res:', res);
Copy the code

The printed values are as follows:

match: hello p1: h p2: ello offset: 0 str: hello world 000 ___
match: world p1: w p2: orld offset: 6 str: hello world 000 ___
match: 000 p1: 0 p2: 00 offset: 12 str: hello world 000 ___
Vmatch: ___ p1: _ p2: __ offset: 16 str: hello world 000 ___
res: Hello World 000 ___
Copy the code

Method 2:

    let s = 'aaa bbb ccc 000 ___';
    let ss = s.replace(/\b\w+\b/g.function (word) {
        return word.substring(0.1).toUpperCase() + word.substring(1);
    });
    console.log(ss); // Aaa Bbb Ccc 000 ___
Copy the code

Example 7 Mask the mobile phone number

    // Suppose we have a cell phone number
    let tel = '13194099515',
	r = ' ',
	tmp = '* * * *';
Copy the code

Method 1:

    r = tel.replace(/\d{4}(? =\d{4}$)/g, tmp); // The first argument is the re (re represents the four digits before the four digits at the end of the match)
    console.log(r); * * * * 9515 / / 131
Copy the code

Method 2:

    r = tel.replace(/(\d{3})(\d{4})/g.'$1' + tmp); // The first argument is re
    console.log(r); * * * * 9515 / / 131
Copy the code

Method 3:

    r = tel.replace(tel.slice(3, -4), tmp); // The first argument is a string
    console.log(r); * * * * 9515 / / 131
Copy the code

Method 4:

    r = tel.replace(/(\d{3})(\d{4})(\d{4})/g.function(match, p1, p2, p3) {
	return p1 + tmp + p3;
    });
    console.log(r); * * * * 9515 / / 131
Copy the code

Mask Phone number reference:

In the string the replace method (www.cnblogs.com/idiv/p/8442.)