javascript字符串将函数替换为正则表达式,我可以在其中插入变量

javascript字符串将函数替换为正则表达式,我可以在其中插入变量,javascript,jquery,Javascript,Jquery,我有以下代码: $(this).html(html.replace(/"expedita"/gi, '<strong>$&</strong>')); $(this.html(html.replace(/“expedita”/gi,$&); 这是工作,但字符串替换是硬编码,我需要能够插入一个变量 $(this).html(html.replace(/"+search+"/gi, '<strong>$&</strong>'));

我有以下代码:

$(this).html(html.replace(/"expedita"/gi, '<strong>$&</strong>'));
$(this.html(html.replace(/“expedita”/gi,$&);
这是工作,但字符串替换是硬编码,我需要能够插入一个变量

$(this).html(html.replace(/"+search+"/gi, '<strong>$&</strong>'));
$(this.html(html.replace(/“+search+”/gi,$&);
搜索是一个变量,我已经指定了一个要替换的值,但这段代码不起作用,似乎我无法将变量插入正则表达式


如何使用regex而不使用硬编码单词,并能够使用任何单词?

要实现灵活、动态的方式来更改替换的表达式,请使用
RegExp
对象

$(this.html(html.replace(新的RegExp(搜索,'g'),“$&”)


其中,
search
是一个变量,其中包含您要替换的表达式。

Try
$(this.html.replace(new RegExp(search,'g'),“$&”)的可能重复项。
@maxit如果其他用户与您有相同的问题,也许我应该给出完整的答案?你怎么看?不要回答重复的问题,把它们标记为重复的问题。