preface

Recently, I encountered a problem about regular expression special characters in my work. After searching in a certain degree, I solved it by myself for a long time. Therefore, I wrote this article to summarize.

Problems encountered

This problem uses regular expressions to search keywords. However, if the keywords contain special symbols, the regular expression error cannot be executed. You need to filter the keywords and convert the special symbols to escaped characters before searching.

instructions

Special characters in regular expressions

  • $
  • ]
  • [
  • )
  • (
  • *
  • +
  • .
  • ?
  • \
  • ^
  • {
  • }

Why do special symbols need to escape

Special symbols have special uses in regular expressions. They cannot be used directly to represent their original meanings. An 🌰 : x | y x and y will be considered either side are consistent. “(z | f ood)” and “zood”, “food” is consistent. The other symbols are not discussed here, but you can read this article if you are interested.

Since the special symbol does not properly represent the original meaning, we need to escape it by adding the symbol \ before the corresponding symbol to make it represent the original meaning.

The API you need to use

String.prototype.replace()

The replace() method returns a new string that replaces some or all of the pattern matches with the replacement value. The pattern can be a string or a regular expression, and the replacement value can be a string or a callback function that is called on every match. If pattern is a string, only the first match is replaced.

As for the usage of replace(), I won’t go into details in this article. If you are interested, you can click the link above to learn more. Next, we will use this API to realize the functions we need to implement.

scenario

Let’s first look at the scenario without special characters

const str = "Fish eat shrimp"
function replace(str, keyword) {
    const regex = new RegExp(` (${keyword}) `."gi")
    console.log("regex", regex)  
    str = str.replace(regex, "Old fish")
    console.log("str", str)
}
replace(str, "Fish") 
replace(str, "shrimp") 

/ / output
// regex /(Fish)/gi
// STR old fish eat shrimp
// regex /(shrimp)/gi
// let's go
Copy the code

Next, let’s look at scenarios with special characters

const str = "[Fish eat shrimp)"
function replace(str, keyword) {
    const regex = new RegExp(` (${keyword}) `."gi")
    str = str.replace(regex, "Old fish")
    console.log("str", str)
}
replace(str, "[")
/ / output
// SyntaxError: Invalid regular expression: /([)/: Unterminated character class
Copy the code

As you can see, the regular expression returns an error when querying for the [symbol, as it does for other special symbols, so let’s fix that.

implementation

I’m going to go straight to the code here

const str = "[Fish eat shrimp)"

/ / escape
function encode(keyword) {
    const reg = /[\[\(\$\^\.\]\*\\\?\+\{\}\\|\)]/gi
    return keyword.replace(reg, (key) = > ` \ \${key}`)}function replace(str, keyword) {
    keyword = encode(keyword)
    console.log("keyword", keyword)
    const regex = new RegExp(` (${keyword}) `."gi")
    str = str.replace(regex, "Old fish")
    console.log("str", str)
}

replace(str, "[")
replace(str, "[Fish")

/ / output
// keyword \[
// shrimp Fish
// keyword \[Fish
// eat shrimp)
Copy the code

conclusion

function encode(keyword) {
    const reg = /[\[\(\$\^\.\]\*\\\?\+\{\}\\|\)]/gi
    return keyword.replace(reg, (key) = > ` \ \${key}`)}Copy the code

This function can escape special characters in regular expressions that need to be used correctly.