我定义了一些简单的正则表达式:
var PIPE= /^\|/;
var START= /^{{/;
var s= "{{hello";
var tSet={PIPE:true, START:true}
var test= "";
for(t in tSet){
if(s.match(t)!=null){
test= test+ s.match(t);
}
}
但它从不匹配任何东西,所以我寻找 t 的类型
typeof t; //returns string
但 t 是一个字符串。如何确保 t 是包含正则表达式的变量?我试过了
for(t in tSet){
var b= new RegExp(t);
if(s.match(b)!=null){
test= test+ s.match(b);
}
}
但是还是不行。我如何对其进行类型转换,以便将 t 识别为正则表达式而不是字符串?
最佳答案
您的代码存在一些问题。首先是 tSet
对象的初始化。您正在使用字符串-> bool 对创建一个对象。 JSON 表示形式为:
{
"PIPE":true,
"START":true
}
接下来,当您使用 for (x in y)
迭代对象时,x
是对象中的每个键,而不是值。
您可以使用tSet[t]
来获取 bool 值。
要从变量名称获取正则表达式值,窗口对象允许这样做:window[t]
。
接下来,您将得到以下结果:
var PIPE= /^\|/;
var START= /^{{/;
var s= "{{hello";
var tSet={PIPE:true, START:true}
var test= "";
for(t in tSet){
if (!tSet[t]) { // If the value is false
continue; // Skip this one and continue to the next
}
if(s.match(window[t])!=null){
test = test + s.match(window[t]);
}
}
然而,在这一点上,有一种更简单的方法,我认为这可能就是您首先尝试做的事情。假设您不需要 bool 值,您应该使用数组:
var PIPE = /^\|/;
var START = /^{{/;
var s = "{{hello";
var tSet = [PIPE, START] // This creates an array with the values of the variables.
var test = "";
for (var i = 0; i < tSet.length; i++) { // For each regex in the array
if(s.match(tSet[i]) != null){
test = test + s.match(tSet[i]);
}
}
关于Javascript RegExp 类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40187661/