Reputation: 19523
I'm trying to extract a resource id using regex into a variable.
So far I managed to match the string, but I'm confused as to how to extract the digits into a separate value.
"/posts/23/edit".match(/\/posts\/(\d*)\/edit/g)
// => ["/posts/23/edit"]
Upvotes: 1
Views: 5624
Reputation: 288620
That's because you use the g
(global) flag, which makes match
ignore capturing groups.
If you are only interested in the first match, just remove the flag.
console.log("/posts/23/edit".match(/\/posts\/(\d*)\/edit/));
// [ "/posts/23/edit", "23" ]
Otherwise you should keep the flag and repeatedly call exec
inside a loop.
var match, rg = /posts\/(\d*)\/edit/g;
while(match = rg.exec("/posts/23/edit -- /posts/24/edit")) {
console.log(match);
}
Upvotes: 2
Reputation: 338376
/\/posts\/(\d*)\/edit/g.exec("/posts/23/edit")
// => ["/posts/23/edit", "23"]
Upvotes: 2