简体   繁体   English

使用JavaScript中的捕获组从变量创建正则表达式

[英]Create regex from variable with capture groups in javascript

How can I create a regex from a variable so that it has a capture group that can then be used in a replace() call? 如何从变量创建正则表达式,使其具有捕获组,然后可以在replace()调用中使用它?

The below is what I have tried so far without success. 以下是到目前为止我没有尝试过的尝试。

 var term = 'test' var r = new RegExp('('+term+')', "ig"); $('#test').html( $('#test').html().replace(r, '<span class="found">'+$1+'</span>') ); // Uncaught ReferenceError: $1 is not defined 
 .found{ background-color:yellow; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <div id="test">This is a test</div> 

I guess this is working as you expect? 我想这按预期工作吗? The main thing is to use $1 inside the replacement string, as <span class="found">$1</span> . 最主要的是在替换字符串中使用$1 ,如<span class="found">$1</span>

 var term = 'test' var r = new RegExp('('+term+')', "ig"); $('#test').html( $('#test').html().replace(r, '<span class="found">$1</span>') ); 
 .found{ background-color:yellow; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <div id="test">This is a test</div> 

You may also discard the capturing group and use the $& backreference in the string replacement pattern that refers to the whole match and also escape the search string since in case it contains special regex chars , it may fail to match: 您还可以丢弃捕获组,并在引用整个匹配项的字符串替换模式中使用$& backreference ,并转义搜索字符串,因为万一其中包含特殊的正​​则表达式字符 ,则可能无法匹配:

 var term = 'test+test' var r = new RegExp(term.replace(/[-\\/\\\\^$*+?.()|[\\]{}]/g, '\\\\$&'), "ig"); $('#test').html( $('#test').html().replace(r, '<span class="found">$&</span>') ); 
 .found{ background-color:yellow; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <div id="test">This is a test+test</div> 

You need to wrap replace expression with a function. 您需要用函数包装替换表达式。

 var term = 'test' var r = new RegExp('('+term+')', "ig"); $('#test').html( $('#test').html().replace(r, function($1){return '<span class="found">'+$1+'</span>'}) ); // Uncaught ReferenceError: $1 is not defined 
 .found{ background-color:yellow; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <div id="test">This is a test</div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM