Welcome to WebmasterWorld Guest from 35.153.73.72

Forum Moderators: open

Message Too Old, No Replies

regexp trouble with global modifier

     
12:20 pm on Jan 22, 2006 (gmt 0)

New User

10+ Year Member

joined:Dec 29, 2004
posts:28
votes: 0


Hi,

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

The following js

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

1:29 pm on Jan 22, 2006 (gmt 0)

Senior Member

WebmasterWorld Senior Member 10+ Year Member

joined:Apr 15, 2004
posts:2047
votes: 0


Hi tores,

I avoided submatch complications by using a range [ab] instead of (aŽb).

var string = 'A=1, B=2, C=3';
var match = string.match(/[ab]=\d+/gi);
alert(match);
1:31 pm on Jan 22, 2006 (gmt 0)

New User

10+ Year Member

joined:Dec 29, 2004
posts:28
votes: 0


Thanx for the tips. Here is how it should be:

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 />');

Must loop through the matches...

(PS: Thanx to d11wtq on devnetwork)

7:24 am on Jan 23, 2006 (gmt 0)

Senior Member

WebmasterWorld Senior Member 10+ Year Member

joined:Apr 15, 2004
posts:2047
votes: 0


Must loop? Not necessarily...

var theString = 'A=1, B=2, C=3';
if(matches = theString.match(/[ab]=\d+/gi))
document.write(matches.join("<br>") [green]/* + "</br>" // perhaps for completeness */[/green]);