简体   繁体   English

JavaScript str.replace用变量

[英]Javascript str.replace with variables

I have found a short script which finds a line with a certain phrase in it and replaces the whole line with a new line. 我发现了一个简短的脚本,该脚本查找其中包含特定短语的行,并将整个行替换为新行。 However I can't work out how to include a variable where it says '#RemoveMe' in the str.replace. 但是我不知道如何在str.replace中的“ #RemoveMe”中包含变量。 (I want to include the variable 'start' which is passed in by the function's trigger, to make --> (/^. start. $/mg, "")) (我想包含由函数的触发器传递的变量“ start”,以使->(/ ^ 。start。 $ / mg,“”))

Any help appreciated... 任何帮助表示赞赏...

        var str = 'line1\n'+
          'line2\n'+
          '#RemoveMe line3\n'+
          'line4';

        var test = str.replace(/^.*#RemoveMe.*$/mg, "");

Thanks. 谢谢。

This is a limitation of the inline regular expression notation. 这是内联正则表达式符号的限制。

If you use new RegExp() you can pass the expression as a string. 如果使用new RegExp() ,则可以将表达式作为字符串传递。

var find = "start";
var regexp = new RegExp("^.*" + find + ".*$", "mg"); // note: no delimiters
str.replace(regexp, "");

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

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