如何简单地在正则表达式替换语句中传递变量?

时间:2014-03-07 01:10:15

标签: javascript regex

我有一个变量字符串短语,我想用变量中的内容修剪字符串的开头,或者没有空格。

var fullphrase = "how can I trim this phrase?";
var cutthis = "how Can i";
var result = fullphrase.replace("/^cutthis ?/i","");

我希望结果是=“修剪这个短语?”

我该如何做到这一点?

3 个答案:

答案 0 :(得分:3)

为什么不将变量传递给replace参数?

var fullphrase = "how can I trim this phrase?";
var cutthis = "how Can i";
var result = fullphrase.replace(new RegExp("^" + cutthis + " ?", 'i'),"");

答案 1 :(得分:3)

var fullphrase = "how can I trim this phrase?";
var cutthis = "how Can i";
var result = fullphrase.replace(new RegExp('^' + cutthis + ' ?', 'i') ,"");

答案 2 :(得分:2)

要动态构建模式,请使用RegExp对象:

var fullphrase = "how can I trim this phrase?";
var cutthis = "how Can i";
var pattern = "^" + cutthis + " ?";
var re = new RegExp(pattern, "i");
var result = fullphrase.replace(re,"");
console.log(result);

查看JSBin demo此操作。