SoFunction
Updated on 2025-03-06

JS regular expression replace string replace method instance code

Introduction to replace() method

The replace() method performs a search replacement operation.

It receives aRegular expressionsAsThe first parameter, receive oneReplace stringAsThe second parameter

It searches for the string that calls it, looking for text that matches the specified pattern.

If the regular expression hasgLogo,replace()Methods replace the stringAll matches; Otherwise, it replaces only the first match.

If the first parameter of the replace() method is a string instead of a regular expression, this method will search by literal value.

Simple usage

let text = 'my name is hu,you NAME is zhang';

// Because strings are non-modified objects, you need to assign a new variable, and you can also reassign ittext = (/name/gi,'like'); // Flag g indicates global matching, flag i indicates case insensitive
(text); // my like is hu,you like is zhang

However, the replace() method has much more than that. For example, in regular expressionsbrackets()The subexpression of the group isFrom left to rightNumbered, and regular expressions can remember the text that each subexpression matches. If the replacement string appears$The symbol is followed by a number (e.g.$1Represents the first set of subexpressions), replace() replaces these two characters with the text matching the specified subexpression.

let str = 'abcdeABCDE';

// where $1 represents the first group (b), $2 represents the second group (c)str = (/(b)(c)/gi,'b$1bc$2c');  // Make b for both sides of b and c for both sides of c
(str); // abbbcccdeAbBbcCcDE

If the regular expression isName the capture group, you can refer to the matching text by name instead of number. If you use the naming capture group, you must write the name to$<name>middle:

let str = 'abcdABCD';
str = (/(?&lt;group1&gt;bc)/gi,'[$&lt;group1&gt;]'); // Put brackets for bc(str); // a[bc]dA[BC]D

Point: Function replacement

In addition to giving the second parameter to replace()Pass the replacement string, you can also pass onefunction, This function will be called and used to calculate the replaced value. If multiple values ​​are matched, each value will be replaced once. This replacement function will receive several parameters when called, the first parameter is the entire text that matches:

let str = 'Xiao Ming has -100 yuan, Xiao Li has 5 yuan, Xiao Zhang has -10 yuan';
// Perform absolute value on the money in itstr = (/-?\d+/g,function(s){
    let num = parseInt(s);
    if(num &lt; 0){
        // If it is less than 0, let it multiply -1        num *= -1; 
    }
    // Return the result to replace it    return num;
})
(str); // Xiao Ming has 100 yuan, Xiao Li has 5 yuan, and Xiao Zhang has 10 yuan

Then, if the regular expression hasCapture Group, then the following parameters are the matching of these capture groupsSubstring. Modify the above code:

let str = 'Xiao Ming has -100 yuan, Xiao Li has 5 yuan, Xiao Zhang has -10 yuan';
// Perform absolute value on the money in itstr = (/(\d+)|(-\d+)/g,function(s,first,last){ 
    // s represents the matching entire string, first represents the first group as a positive number, last represents the second group as a negative number,    if(first){
        // If the positive number is returned directly        return first;
    }else{
        // If the negative number is multiplied -1        return parseInt(last)*-1;
    }
})
(str); // Xiao Ming has 100 yuan, Xiao Li has 5 yuan, and Xiao Zhang has 10 yuan

Supplement: Replace special characters

To replace special characters, such as -/\\^$*+?.()|[]{}), you need to escape them with a backslash.

If given the string this\\-is\\-my\\-url, all escaped minus signs ( \\-) are required to replace all escaped minus signs (-).

You can use replace() to do it:

const myUrl = 'this\-is\-my\-url';
const newUrl = (/\\-/g, '-');
(newUrl); // this-is-my-url

Or use new Regexp():

const myUrl = 'this\-is\-my\-url';
const newUrl = (new RegExp('\-', 'g'), '-');
(newUrl); // this-is-my-url

In the second example, there is no need to use a backslash to escape the backslash.

Summarize

This is the article about JS regular expression replacement string replace() method. For more related JS regular expression replacement string replace() content, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!