如何使用变量动态构建正则表达式对象

How to use variable to dynamically build regular expression object

本文关键字:正则表达式 对象 构建 动态 何使用 变量      更新时间:2023-09-26

我想动态构建正则表达式,如:

function buildReges(regex_string) {
   // here I want to use the string format to build a regex
   // like / + regex_string +/
}

我想知道我该怎么做?或者如果有一种方法,我可以把字符串变成正则表达式对象?

使用RegExp构造函数:

function buildReges(regex_string) {
   // here I want to use the string format to build a regex
   var re = new RegExp(regex_string);
}

如果你想使用标志,你可以使用第二个参数:

new RegExp(regex_string, 'gi');