jcarias
jcarias

Reputation: 21

Javascript extract only the capturing group

I need to extract an id from a string but I can't only the ID. I'm trying to user a pattern that works fine in Java, but in JS it yields more results than I like. Here is my code:

var reg = new RegExp("&topic=([0-9]+)");

When applying execute this against the string "#p=activity-feed&topic=1697"

var results = reg.exec("#p=activity-feed&topic=1697");

I was hoping to get just the number part (1697, in this case) because this was preceded by "&topic=", but this is returning two matches:

0: "&topic=1697"
1: "1697"

Can someone help me to get ["1967","9999"] from the string "#p=activity-feed&topic=1697&no_match=1111&topic=9999"?

Upvotes: 0

Views: 57

Answers (2)

Jared Smith
Jared Smith

Reputation: 21994

While Noah's answer is arguably more robust and flexible, here's a regex-based solution:

var topicRegex = /&topic=(\d+)/g; // note the g flag
var results = [];
var testString = "p=activity-feed&topic=1697&no_match=1111&topic=9999";
var match;
while (match = reg.exec(testString)) {
  results.push(match[1]); // indexing at 1 pulls capture result
}
console.log(results); // ["1697", "9999"]

Works for any arbitrary number of matches or position(s) in the string. Note that the matches are still strings, if you want to treat them as numbers you'll have to do something like:

var numberized = results.map(Number);

Upvotes: 0

Noah Freitas
Noah Freitas

Reputation: 17430

Assuming the browser support is right for your use case, URLSearchParams can do all of the parsing for you:

var params = new URLSearchParams('p=activity-feed&topic=1697&no_match=1111&topic=9999');
console.log(params.getAll('topic'));

Upvotes: 2

Related Questions