2

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.

1
  • The second time you got multiple :s Commented Sep 8, 2012 at 19:01

2 Answers 2

1

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]);
Sign up to request clarification or add additional context in comments.

Comments

0

Use content.match instead of regX.exec

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.