escapeStringRegexp 函数的作用

escapeStringRegexp 函数的作用:

函数作用

escapeStringRegexp 函数用于转义字符串中的正则表达式特殊字符,使该字符串可以安全地用作正则表达式的字面量,而不会被误认为是正则元字符。

实现原理

export const escapeStringRegexp = (string = '') =>
  string.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d')

该函数执行了两次替换:

  1. 第一次替换: replace(/[|\\{}()[\]^$+*?.]/g, '\\$&')

    • 转义以下特殊字符:| \ { } ( ) [ ] ^ $ + * ? .
    • 在每个特殊字符前添加反斜杠 \
    • $& 表示匹配到的原始字符
  2. 第二次替换: replace(/-/g, '\\x2d')

    • 将连字符 - 替换为 \x2d
    • 使用十六进制转义序列避免 - 在字符类中的特殊含义

使用场景示例

// ❌ 不转义的情况 - 会出错
const userInput = "file.js"
const regex = new RegExp(`\.${userInput}`) // 意图匹配 .file.js,但 . 会被当作"任意字符"

// ✅ 使用 escapeStringRegexp
import { escapeStringRegexp } from './strings'
const userInput = "file.js"
const regex = new RegExp(`\.${escapeStringRegexp(userInput)}`)
// 实际正则:\.file\.js - 正确匹配字面量 ".file.js"

更多示例

escapeStringRegexp('$100')           // → '\$100'
escapeStringRegexp('hello?')         // → 'hello\?'
escapeStringRegexp('file.txt')       // → 'file\.txt'
escapeStringRegexp('[test]')         // → '\[test\]'
escapeStringRegexp('a-b-c')          // → 'a\x2db\x2dc'

// 实际应用
const searchText = 'hello.js'
const escaped = escapeStringRegexp(searchText)
const regex = new RegExp(escaped, 'gi')
// 可以安全地搜索字符串 "hello.js",而不会将 . 作为通配符

为什么需要这个函数?

当用户输入或动态字符串需要作为正则表达式的一部分时,如果不转义特殊字符,会导致:

  • 正则表达式语法错误
  • 匹配结果不符合预期
  • 潜在的安全问题(ReDoS 攻击)

这个函数从 sindresorhus/escape-string-regexp 项目 fork 而来,是处理这类问题的标准解决方案。

posted @ 2026-01-06 23:21  龙陌  阅读(2)  评论(0)    收藏  举报