一、使用正则表达式时报错
使用new RegExp()对keyword进行匹配时,当keyword字符串中出现特殊符号时,匹配失败并报错。故需要在调用RegExp()之前对所有特殊字符进行转义
const regex = new RegExp(keyword, 'gi');
const matchResult = nodeText.match(regex);

image
二、使用replace进行处理
1. 定义特殊字符
const pattern = /[`~!@#_$%^&*()=|{}':;',\\\[\\\].<>/?~!@#¥……&*()——|{}【】‘;:”“'。,、?\s]/g;
2. 进行replace(在第二个参数中获取到具体match的变量)
escapeSpecialCharacter(str: string) {
const pattern = /[`~!@#_$%^&*()=|{}':;',\\\[\\\].<>/?~!@#¥……&*()——|{}【】‘;:”“'。,、?\s]/g;
return str.replace(pattern, (match => '\\' + match));
}