Forum Moderators: open

Message Too Old, No Replies

Calling RegEx Experts

2nd recall on RegEx not working

         

vol7ron

2:15 pm on Oct 2, 2009 (gmt 0)

10+ Year Member



Here's a simple example:
[pre]
function testRegEx(){
var str = "id1";
var ret = /(\w+?)(\d+¦\b)/ig.exec(str);
alert(ret);
return;
}
[/pre]

If you call it from a button or some click event from the HTML page this is what the output would be:

[pre]
Pass 1: id1,id,1
Pass 2: null
Pass 3: id1,id,1
Pass 4: null
[/pre]

The odd number passes are correct.

It's like I have to call .exec() twice to get what I want.

Thanks for any help,
vol7ron

vol7ron

2:23 pm on Oct 2, 2009 (gmt 0)

10+ Year Member



What I mean is that my workaround is to do this:
[pre]
function testRegEx(){
var str = "id1";
var re = /(\w+?)(\d+¦\b)/ig;
var ret = re.exec(str);
re.exec();
alert(ret);
return;
}
[/pre]

But, I don't know why that's necessary.

vol7ron

2:50 pm on Oct 2, 2009 (gmt 0)

10+ Year Member



Okay I discovered the culprit: the global flag

The re.lastIndex property is stored, so the second time the function is called, it starts from that position. Example:

[pre]
Pass #: alert(ret) [beg lastIndex - end lastIndex]
---------------------------------------------------
Pass 1: id1,id,1 [lastIndex:0 - lastIndex:3]
Pass 2: null [lastIndex:3 - lastIndex:0]
Pass 3: id1,id,1 [lastIndex:0 - lastIndex:3]
Pass 4: null [lastIndex:3 - lastIndex:0]
[/pre]

I've tried "delete(re)" and "delete re" at the end of the function, which doesn't destroy the re itself. And apparently redefining the regular expression at the beginning of the function, isn't replacing the previous (ex "var re = /(\w+?)(\d+¦\b)/ig;"). So I don't know how to destroy the RegEx, it's seemingly global and indestructible/irreplaceable.

However, the good news is that the property is read/write, so new code:

[pre]
function testRegEx(){
var str = "id1";
var re = /(\w+?)(\d+¦\b)/ig;
var ret = re.exec(str);
re.lastIndex = 0;
alert(ret);
return;
}

Pass #: alert(ret) [beg lastIndex - end lastIndex]
---------------------------------------------------
Pass 1: id1,id,1 [lastIndex:0 - lastIndex:3]
Pass 2: id1,id,1 [lastIndex:0 - lastIndex:3]
Pass 3: id1,id,1 [lastIndex:0 - lastIndex:3]
Pass 4: id1,id,1 [lastIndex:0 - lastIndex:3]
[/pre]