Javascript 将CSS添加到每个RegExp匹配项

Javascript 将CSS添加到每个RegExp匹配项,javascript,jquery,css,regex,Javascript,Jquery,Css,Regex,我需要检测一些随机正则表达式,然后将它们应用于每个正则表达式,比如: 将匹配[0]替换为匹配[0] 将Match[1]替换为Match[1] 将Match[n]替换为Match[n] 我试过这个 .replace(randomregexp, "<span class='found'>$1</span>"); 如果您可以发布模式代码,这将很有帮助,但请尝试.wrap(')您需要使用wrap功能。试着这样做: .wrap('<span class="found"&

我需要检测一些随机正则表达式,然后将它们应用于每个正则表达式,比如:

  • 匹配[0]
    替换为
    匹配[0]
  • Match[1]
    替换为
    Match[1]
  • Match[n]
    替换为
    Match[n]
我试过这个

.replace(randomregexp, "<span class='found'>$1</span>");

如果您可以发布模式代码,这将很有帮助,但请尝试
.wrap(')
您需要使用
wrap
功能。试着这样做:

.wrap('<span class="found"></span>')
.replace(randomregexp, "<span class='found'>$&</span>");

确保将匹配项包装在
中。如果没有匹配的文本,则只显示
$1

texts = '('+document.getElementById("query").value+')';
那么$1应该适用于匹配的子字符串

'hello'.replace(/(\w+)/,"<span class='found'>$1</span>") 
// Outputs: "<span class='found'>hello</span>"
'hello'。替换(/(\w+/,“$1”)
//输出:“你好”

是否将替换方法应用于整个html内容?你能发一把小提琴吗?检查结果谢谢!它与.replace(randomregexp,$&)一起工作;没问题,我最初发布的是使用
$&
,但后来我开始过度思考;)
'hello'.replace(/(\w+)/,"<span class='found'>$1</span>") 
// Outputs: "<span class='found'>hello</span>"