Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript regular expressions - exec infinite loop

I'm trying to get a link text using regex. there are possibly several links that may match the pattern and I want to get the furthest one until the 4th. Here is my JS code:

var level=1;
while ( _match = /<a href="http:\/\/www.mysite.com\/x\/(?:.*)>(.*)<\/a>/img.exec(_html)){
    if (level < 5)  (_anchor_text=_match[1]);
    level ++;
}

The problem is that this code enters infinite loop on IE (works well on FF), although the pattern exists. Any help is appreciated.

like image 338
Nir Avatar asked May 20 '09 16:05

Nir


Video Answer


1 Answers

RegExp.exec, I believe, makes use of the lastIndex property and continually modifies it to make things like "global group capturing" possible; for it to work you need to have a single regular expression. Currently you're creating a new one on every iteration so it won't work...

Try this:

var level = 1;
var pattern = /<a href="http:\/\/www.mysite.com\/x\/(?:.*)>(.*)<\/a>/img;
var _match;
while ( _match = pattern.exec(_html)){
     if (level < 5)  (_anchor_text=_match[1]);
     level ++;
}
like image 156
James Avatar answered Sep 28 '22 01:09

James