Reputation: 23
I'm trying JS regX to match some values and replace them with the markup. So here is the code I tried.
content = '<p>[dfp:advertisement:leaderboard:750x90]</p>text here<p>[dfp:advertisement:box1:300x250]</p>';
var regX = /([a-zA-Z0-9]*):([0-9]*x[0-9]*)/g;
match = regX.exec(content);
Okay, the issue is this will only match the first value, not the second one. I've added /g
but no luck yet.
Thanks for looking.
Upvotes: 2
Views: 319
Reputation: 59617
A single call to exec
will only return the first match, even with the g
flag. But the regex will contain state such that subsequent multiple calls to exec
using the same regex will return the following matching items.
From the MDN exec
documentation:
The returned array has the matched text as the first item, and then one item for each capturing parenthesis that matched containing the text that was captured
[ ... ]
If your regular expression uses the "g" flag, you can use the exec method multiple times to find successive matches in the same string.
So this code will alert
the first two matches from your example:
var content = '<p>[dfp:advertisement:leaderboard:750x90]</p>text here<p>[dfp:advertisement:box1:300x250]</p>';
var regX = /([a-zA-Z0-9]*):([0-9]*x[0-9]*)/g;
var match = regX.exec(content);
var match2 = regX.exec(content);
alert(match[0]);
alert(match2[0]);
As others have already mentioned, you can instead use match
on a string to return an array with the multiple matches.
So, similar to the above code, this code will alert
the first two matches from your example:
var content = '<p>[dfp:advertisement:leaderboard:750x90]</p>text here<p>[dfp:advertisement:box1:300x250]</p>';
var regX = /([a-zA-Z0-9]*):([0-9]*x[0-9]*)/g;
var match = content.match(regX);
alert(match[0]);
alert(match[1]);
Upvotes: 1