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"]
/\/posts\/(\d*)\/edit/g.exec("/posts/23/edit")
// => ["/posts/23/edit", "23"]
RegExp#exec is actually necessary if you didn't know it before. Why would I have to write an excerpt of the documentation?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);
}
/ggives you the digits in the second element in the resulting array. Any particular reason you put it there?