带有动态正则表达式的Javascript String.replace? [英] Javascript String.replace with dynamic regular expressions?
本文介绍了带有动态正则表达式的Javascript String.replace?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码,但是我需要在运行时向正则表达式对象( regex2
)注入一些不同的东西。但是,text.replace似乎不喜欢正则表达式的字符串对象,所以我该如何使它工作?
I have the following code, which works, but I need to inject some different stuff into the regular expression object (regex2
) at runtime. However, text.replace does not seem to like a string object for the regular expression, so how can I make this work?
var regex2 = /\|\d+:\d+/;
document.write("result = " + text.replace(regex2, '') + "<br>");
推荐答案
您可以使用字符串制作正则表达式对象 RegExp 构造函数:
You can make a regular expression object from a string using the RegExp constructor function:
var regExp = new RegExp(myString); // regex pattern string
text.replace(regExp, '');
这篇关于带有动态正则表达式的Javascript String.replace?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文