对于一个非常简单的 javascript 模板引擎,我需要检查给定的字符串 "is" javascript 代码(如 if-else
、for-loops
或 while-loops
)。因此,我使用了这个非常简单的正则表达式 /(:|=|{|})/g
( "tested" here )。虽然这个正则表达式几乎在任何时候都有效,但在某些情况下当我在循环中使用它时它会以某种方式失败:
// Very simple regex to check if string "is" javascript code
var regFunc = /(:|=|{|})+/g;
// For testing: a simple javascript array
var testArray = [
// expected: false, is: false
'string',
// expected: true, is: true
'for(var i=0; i<total;i++) {',
// expected: true, is: false (??)
'}',
// expected: true, is: true
'}'
];
for( var i = 0; i < testArray.length; i++ ) {
console.log(
testArray[ i ],
regFunc.test( testArray[ i ] )
);
}
您可以在 JSBin 上查看控制台输出.所以我想知道为什么第一个“{”输出 false
而第二个输出 true
(这是我对两者的期望)?
最佳答案
As with exec (or in combination with it), test called multiple times on the same global regular expression instance will advance past the previous match.
这意味着每次测试字符串时都必须重新初始化正则表达式对象。
关于javascript - 使用正则表达式检查字符串 "is"javascript 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26238188/