您的解决方案如下:
Pass a variable to regular expression.
我实现的方法是从一个文本字段获取值,这个文本字段是要替换的,另一个是“替换为”文本字段,从变量中的文本字段获取值,并将变量设置为regexp函数以进一步替换。在我使用jquery的情况下,也可以只使用javascript。
javascript代码:
var replace =document.getElementById("replace}"); // getting a value from a text field with I want to replace
var replace_with = document.getElementById("with"); //Getting the value from another text fields with which I want to replace another string.
var sRegExInput = new RegExp(replace, "g");
$("body").children().each(function() {
$(this).html($(this).html().replace(sRegExInput,replace_with));
});
这段代码是关于一个按钮的onclick事件的,你可以把它放到一个函数中调用。
所以现在可以在replace函数中传递变量。