user1657151
user1657151

Reputation: 23

Regex for filtering keywords from a string

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

Answers (2)

pb2q
pb2q

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

Delta
Delta

Reputation: 4328

Use content.match instead of regX.exec

Upvotes: 0

Related Questions