Javascript RegExp 类型转换

标签 javascript regex casting

我定义了一些简单的正则表达式:

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/

相关文章:

javascript - 如何确保当我将鼠标悬停或在消失之前添加延迟时我的子菜单不会消失

javascript - 为什么 [^...] in/RegExp/不安全?

c++ - reinterpret_cast to void* 不使用函数指针

asp.net - "No quotes in a string"的正则表达式是什么?

Java:我将如何使用正则表达式过滤字符串以查找特定的字符集?

c# - 是否有将对象转换为小数的单行方法?

java - Gson 库,将 JsonObject 转换为 MyObject

javascript - 如何根据所有下拉值的测试设置按钮文本?

javascript - 出血区域适用于通过鼠标拖动移动的对象,但不适用于键盘箭头键

javascript - 将依赖对象传递给 Javascript 模块时遇到问题