使用正则表达式突出显示字符串中的变量单词 [英] Highlighting variable word in a string using regular expression
本文介绍了使用正则表达式突出显示字符串中的变量单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
var stringToHighlight = [userinput] // may be any string like "foo", "bar" or "."
var stringToBeHighlighted = [any text] // Lorem Ipsum ...
到目前为止我有
var regex = new RegExp(stringToHighlight, "g")
var highlightedString = stringToBeHighlighted.replace(regex, "<span class='highlight'>$&</span>")
这不适用于角色。例如,因为它被解释为正则表达式元字符。但不是实际的字符。导致所有文本突出显示。如何排除这些特殊的元字符?
This doesn't work for the character "." for example, because it is being interpreted as the regular expression metacharacter . but not the actual character "." resulting in all the text being highlighted. How do I exclude those special metacharacters?
推荐答案
JS没有任何内置函数来转义正则表达式中的元字符,但是您可以使用此功能(来自此答案):
JS doesn't have any built in function to escape meta characters in regex, but you could use this function (from this answer):
function quotemeta(str){
return str.replace(/[.+*?|\\^$(){}\[\]-]/g, '\\$&');
}
将使用如下:
var regex = new RegExp(quotemeta(stringToHighlight), "g");
这篇关于使用正则表达式突出显示字符串中的变量单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文