Nikola
Nikola

Reputation: 15038

Uncaught SyntaxError: Invalid regular expression in Chrome, FF and IE fine

This line of code:

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

works perfect in Firefox (6.0), and in IE (7.0), but not in Chrome (13.0.782.112)

do you have any idea why?

Upvotes: 1

Views: 10110

Answers (2)

HBP
HBP

Reputation: 16033

Put a try/catch around your code and display the value that is causing the exception :

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

Upvotes: 4

Aleks G
Aleks G

Reputation: 57316

The problem is that your arrCategorySort[i] as a string contains special characters as far as the RegExp parser is concerned (e.g. {} and []). With your string in place, you're trying to parse 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/

After your (a,b) in the beginning, in {} you have var ... however {} mean repeated pattern and expect to have a number between them (or two numbers). What you really need is to escape all special chars: {}[]|()\,.*+ - by prepending '\' character in front of each of them. (There may be a couple more, escapes me at the moment.)

Upvotes: 1

Related Questions