最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Uncaught SyntaxError: Invalid regular expression in Chrome, FF and IE fine - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question asked Aug 22, 2011 at 10:20 NikolaNikola 15k21 gold badges106 silver badges170 bronze badges 4
  • What's in arrCategorySort[i]? – Lucero Commented Aug 22, 2011 at 10:24
  • in arrCategorySort[i] there is one word (or maybe even more words) - (it's a loop through these items: var arrCategorySort = new Array ("menu", "food", "drink", "drinks", "2 course", "three course"); Could it be the error appears when two words are in? – Nikola Commented Aug 22, 2011 at 10:29
  • Those that you listed should work fine, however some binations may be invalid (with all sorts of braces and brackets, backslashes etc.). IE and FF may handle invalid regexes in a different way than Chrome. – Lucero Commented Aug 22, 2011 at 10:34
  • What is the full error message? – HBP Commented Aug 22, 2011 at 11:13
Add a ment  | 

2 Answers 2

Reset to default 4

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] + '"');  
}

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.)

发布评论

评论列表(0)

  1. 暂无评论