2012-04-28 153 views
2

可能重复:
How do you pass a variable to a Regular Expression JavaScript?
javascript regular expressions with variables?替换功能

我想创建一个函数,它使用类似

function(str, source, target) 
    { 
    /* str = string, source = text to replace, target = text with replace */ 
    str.replace(/source/i, target); 
    } 
正则表达式在JavaScript替换文本

现在我的问题是在这里,这个函数将source视为一个文本而不是一个变量。我怎样才能解决这个问题?

+1

的可能的复制(http://stackoverflow.com/questions/4237051/javascript-regular-expressions-with-variables) ,和[正则表达式 - 你如何将一个变量传递给正则表达式的JavaScript?](http://stackoverflow.com/questions/494035/how-do-you-pass-a-variable-to-a-regular-expression -javascript)。 – 2012-04-28 19:40:44

+0

织补。我讨厌什么时候发生。 – 2012-04-28 19:41:06

回答

0

你正在寻找:[?与变量的JavaScript正则表达式]

var re = new RegExp(source, "i"); 
return str.replace(re, target);