[英]JavaScript RegEx: How to create a RegEx pattern using a specific value from a Variable?
I have this variable: 我有这个变量:
var search = "dummy";
var replace = "<strong>" + search + "</strong>";
var contents = "my contents are here and this dummy value should be bolded...";
contents.replace(/search/gi, replace);
So, How can I set this "search" variable under my RegEx pattern, followed with /gi settings for my match. 因此,如何在RegEx模式下设置此“搜索”变量,然后为我的匹配设置/ gi设置。
try 尝试
new RegExp('yourSearchHere', 'gi');
you should also be aware of the fact, that you have to escape certain sequences. 您还应该意识到以下事实:必须转义某些序列。 Btw.
顺便说一句。 you have to double escape these when you're constructing a regex like this (new RegExp('\\\\n') -> matches \\n)
在构造这样的正则表达式时,必须将它们加倍转义(新的RegExp('\\\\ n')->匹配\\ n)
You can also create a regular expression using the RegExp object: 您还可以使用RegExp对象创建正则表达式:
search = "dummy";
x = new RegExp(search,"gi");
var search = "dummy";
var replace = "<strong>" + search + "</strong>";
var contents = "my contents are here and this dummy value should be bolded...";
window.alert(contents.replace(x, replace));
You can use backreferences : The $1 is remembering what you matched with the regular expression. 您可以使用反向引用 :$ 1会记住您与正则表达式匹配的内容。 It does this because the word you are searching for is placed inside round brackets which form a capturing group.
这样做是因为您要搜索的单词放在组成捕获组的圆括号内。
var contents = "my contents are here and this dummy value should be bolded...";
function makeStronger( word, str ) {
var rxp = new RegExp( '(' + word +')', 'gi' );
return str.replace( rxp, '<strong>$1<\/strong>' );
}
console.log( makeStronger( 'dummy', contents ) );
// my contents are here and this <strong>dummy</strong> value should be bolded...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.