在span标记中包装动态不敏感字符串 [英] wrap dynamic insensitive string in span tag
问题描述
我正在尝试将动态不敏感字符串包装在span标记中,但输出中有$ 1。请帮助我。
I am trying to wrap the dynamic insensitive string in span tag but $1 is coming in output. Please help me.
function focusSearchValue(data, value){
var regEx = new RegExp((value), "ig");
data = data.replace(regEx, "<span class=''>$1</span>");
console.log(data);
}
focusSearchValue('SharePoint 2016, Team Collaboration Software Tools', 'sharepoint');
推荐答案
值
周围的括号不是模式的一部分,因此,你的正则表达式没有定义捕获组, $ 1
可以从字符串替换模式引用。这就是 $ 1
作为替换结果作为文字字符串传递的原因。
The parentheses around value
are not part of the pattern, and thus, your regex has no capturing group defined, that $1
could refer to from the string replacement pattern. That is why $1
is passed as a literal string as the replacement result.
你需要使用 $&
引用整个匹配(参见 String#replace
将字符串指定为参数部分),并返回字符串:
You need to use $&
to refer to the whole match (see String#replace
"Specifying a string as a parameter" section), and return the string:
function focusSearchValue(data, value){
var regEx = new RegExp(value.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), "ig");
return data.replace(regEx, "<span class=''>$&</span>");
}
console.log(focusSearchValue('SharePoint 2016, Team Collaboration Software Tools', 'sharepoint'));
因为你将变量传递给应该是的正则表达式引擎解析为文字字符串,建议转义所有可能作为特殊正则表达式元字符的特殊字符,因此添加了转义 .replace(/ [ - \ / \\ ^ $ * +? 。()| [\] {}] / g,'\\ $&')
。
Since you pass a variable to the regex engine that should be parsed as a literal string, it is advisable to escape all special chars that may act as special regex metacharacters, hence the added escaping .replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
.
这篇关于在span标记中包装动态不敏感字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!