Page 1 of 1

Javascript global modifier question

Posted: Sun Jan 22, 2006 6:25 am
by tores
Hi,

Seems that I've misunderstood the behaviour of the global modifier, g, in Javascript RegExp...

The following js

Code: Select all

var string = 'A=1, B=2, C=3';
var match = (/(a¦b)=\d+/gi).exec(string);
document.write(match);
document.close();
should match both A=1 and B=2, but only A=1 is matched. What am I missing?

tores

Posted: Sun Jan 22, 2006 7:12 am
by Chris Corbyn
You've understood it correctly but in order for it to be proccessed you need to use a while(true) loop ;)

Code: Select all

var theString = 'A=1, B=2, C=3';
var re = new RegExp('[ab]=\\d+', 'gi');
while (matches = re.exec(theString))
    document.write(matches.toString() + '<br />');
NOTE: I find it bad habit to name variables "match" and "string" since these are reserved words... ;)