Javascript global modifier question

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
tores
Forum Contributor
Posts: 120
Joined: Fri Jun 18, 2004 3:04 am

Javascript global modifier question

Post 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
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post 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... ;)
Post Reply