Nick Vanderbilt
Nick Vanderbilt

Reputation: 38420

Javascript regular expression is returning # character even though it's not captured

text = 'ticket number #1234 and #8976 ';
r = /#(\d+)/g;

var match = r.exec(text);

log(match); // ["#1234", "1234"]

In the above case I would like to capture both 1234 and 8976. How do I do that. Also the sentence can have any number of '#' followed by integers. So the solution should not hard not be hard coded assuming that there will be at max two occurrences.

Update: Just curious . Checkout the following two cases.

var match = r.exec(text); // ["#1234", "1234"]

var match = text.match(r);  //["#1234", "#8976"]

Why in the second case I am getting # even though I am not capturing it. Looks like string.match does not obey capturing rules.

Upvotes: 1

Views: 86

Answers (3)

meouw
meouw

Reputation: 42140

Here's another way

var text = 'ticket number #1234 and #8976 ';
var r = /#(\d+)/g;

var matches = [];
text.replace( r, function( all, first ) {
    matches.push( first )
});

log(matches);

//  ["1234", "8976"]

Upvotes: 0

kennytm
kennytm

Reputation: 523224

exec it multiple times to get the rest.

while((match = r.exec(text)))
  log(match);

Upvotes: 1

Gumbo
Gumbo

Reputation: 655219

Use String.prototype.match instead of RegExp.prototype.exec:

var match = text.match(r);

That will give you all matches at once (requires g flag) instead of one match at a time.

Upvotes: 1

Related Questions