未捕获的SyntaxError:无效的正则表达式在Chrome, FF和IE fine



这行代码:

if ( new RegExp("\b" + arrCategorySort[i]+ "\b", "g").test(titleText) )
{
    catFound = true;
}

可以在Firefox(6.0)和IE(7.0)中完美运行,但不能在Chrome(13.0.782.112)中运行

你知道为什么吗?

在代码周围放置try/catch,并显示导致异常的值:

try {
    if ( new RegExp("\b" + arrCategorySort[i]+ "\b", "g").test(titleText) )
        catFound = true;
}
catch (e) {
    confirm (e + ' : at index ' + i + ', category is "' + arrCategorySort[i] + '"');  
}

问题是您的arrCategorySort[i]作为字符串包含特殊字符,就RegExp解析器而言(例如{}[])。字符串就位后,您将尝试解析regexp

 /bfunction (a,b){var c=b||window,d=[];for(var e=0,f=this.length;e<f;++e){if(!a.call(c,this[e],e,this))continue;d.push(this[e])‌​}return d}b/

在开始的(a,b)之后,在{}中,您有var ...,但{}表示重复模式,并期望在它们之间有一个数字(或两个数字)。您真正需要的是转义所有特殊字符:{}[]|(),.*+ -通过在每个字符前面加上''字符。(可能还有更多,我现在想不起来了。)

最新更新