首页 新闻 会员 周边

typescript: RegExp 创建正则表达式对象时如何对字符串进行 escape

0
悬赏园豆:30 [已解决问题] 解决于 2023-12-05 18:48

比如下面的 typescript 使用 RegExp 的代码

const regex = new RegExp(String.raw`${prefix}${src.data}`, 'g')
text = text.replace(regex, prefix + newLink)

RegExp 的第一个参数值是 [PIO.png]: ../_resources/PIO.png,希望直接使用原始字符串,如果不进行转义,[,.等字符会被当正则的元字符,请问如何进行转义?

问题补充:

C# 中有 Regex.Escape()

dudu的主页 dudu | 高人七级 | 园豆:30994
提问于:2023-12-05 17:59
< >
分享
最佳答案
0

方法1:使用 npm 包 lodash 中内置的 escapeRegExp 方法

import { escapeRegExp } from 'lodash'
const regex = new RegExp(escapeRegExp(String.raw`${prefix}${src.data}`), 'g')

方法2:使用 npm 包 escape-string-regexp

import escapeStringRegexp from 'escape-string-regexp';
const escapedString = escapeStringRegexp('How much $ for a 🦄?');
//=> 'How much \\$ for a 🦄\\?'

方式3: 自己实现,来自 https://stackoverflow.com/a/6969486

function escapeRegExp(string) {
    return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
dudu | 高人七级 |园豆:30994 | 2023-12-05 18:47
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册