使用字符串变量动态创建RegExps [英] Create RegExps on the fly using string variables
问题描述
说我想让以下内容重复使用:
Say I wanted to make the following re-usable:
function replace_foo(target, replacement) {
return target.replace("string_to_replace",replacement);
}
我可能会这样做:
function replace_foo(target, string_to_replace, replacement) {
return target.replace(string_to_replace,replacement);
}
使用字符串文字这很容易。但是,如果我想让正则表达式变得更加棘手呢?例如,假设我要替换所有但 string_to_replace
。本能地,我会尝试通过以下方式扩展上述内容:
With string literals this is easy enough. But what if I want to get a little more tricky with the regex? For example, say I want to replace everything but string_to_replace
. Instinctually I would try to extend the above by doing something like:
function replace_foo(target, string_to_replace, replacement) {
return target.replace(/^string_to_replace/,replacement);
}
这似乎不起作用。我的猜测是它认为 string_to_replace
是一个字符串文字,而不是表示字符串的变量。是否可以使用字符串变量动态创建JavaScript正则表达式?如果可能的话,这样的事情会很棒:
This doesn't seem to work. My guess is that it thinks string_to_replace
is a string literal, rather than a variable representing a string. Is it possible to create JavaScript regexes on the fly using string variables? Something like this would be great if at all possible:
function replace_foo(target, string_to_replace, replacement) {
var regex = "/^" + string_to_replace + "/";
return target.replace(regex,replacement);
}
推荐答案
new RegExp(string,flags)
其中 flags
是 g
或我
。所以
'GODzilla'.replace( new RegExp('god', 'i'), '' )
评估为
zilla
这篇关于使用字符串变量动态创建RegExps的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!