Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript正则表达式:保存匹配值_Javascript_Regex_String - Fatal编程技术网

Javascript正则表达式:保存匹配值

Javascript正则表达式:保存匹配值,javascript,regex,string,Javascript,Regex,String,我在JS中有以下表达式(typescript,但我认为每个人都理解它传输到什么): markString(文本:string){ const regEx=new RegExp(this.partToHighlight'ig'); 返回text.replace(regEx,`${this.partToHighlight}`); } 问题在于,通过这种方式,使用“ig”-选项,匹配值可以有任何大小写,上限或下限,但始终由partToHighlight-值替换。相反,函数应该读取匹配的值,保存它并输

我在JS中有以下表达式(typescript,但我认为每个人都理解它传输到什么):

markString(文本:string){
const regEx=new RegExp(this.partToHighlight'ig');
返回text.replace(regEx,`${this.partToHighlight}`);
}

问题在于,通过这种方式,使用“ig”-选项,匹配值可以有任何大小写,上限或下限,但始终由
partToHighlight
-值替换。相反,函数应该读取匹配的值,保存它并输出它,并用HTML标记包围。我该怎么做?我很确定这是一个重复的问题,但我找不到以前问过的问题。

您需要替换为找到的匹配项,
$&

markString(text: string) {
    const regEx = new RegExp(this.partToHighlight, 'ig');
    return text.replace(regEx, "<mark>$&</mark>");
}
markString(文本:string){
const regEx=new RegExp(this.partToHighlight'ig');
返回文本。替换(regEx,“$&”);
}
使用
$&
,您可以用找到的匹配替换为找到的相同文本,并且不需要硬编码替换,也不需要使用任何回调


有关更多详细信息,请参阅。

如注释中所述,您需要使用或在
replace()
方法中指出匹配的子字符串:

const regEx = new RegExp(this.partToHighlight, 'ig');
return text.replace(regEx, `<mark>$&<\/mark>`);
const regEx=new RegExp(this.partToHighlight,'ig');
返回text.replace(regEx,`$&`);

实际上,我在回答中提供了一个指向
$&
的更合适的链接,因为您还提供了基于字符串替换的反向引用解决方案(这和我的一样,只是没有必要在替换模式中转义
/
,因为字符串文本中的单个
\
将被引擎删除)。@WiktorStribiżew很好地指出,谢谢,我编辑了我的答案。
const regEx = new RegExp(this.partToHighlight, 'ig');
return text.replace(regEx, `<mark>$&<\/mark>`);