1

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"]
2
  • Check SO Docs Javascript Regex Groups Commented Aug 28, 2016 at 18:37
  • 1
    Removing the /g gives you the digits in the second element in the resulting array. Any particular reason you put it there? Commented Aug 28, 2016 at 18:37

2 Answers 2

2
/\/posts\/(\d*)\/edit/g.exec("/posts/23/edit")
// => ["/posts/23/edit", "23"]
Sign up to request clarification or add additional context in comments.

8 Comments

The answer itself could use an explanation…
(I didn't do any downvotes, but a bit of an explanation wouldn't hurt to teach the guy why not only how)
@Biffen Actually, I expect the OP do do some reading on their own. Really. This is a basic problem. The terseness of the answer testifies this. Flipping through the docs of RegExp#exec is actually necessary if you didn't know it before. Why would I have to write an excerpt of the documentation?
@ave I figured you are just missing a basic hint here and would be fine on your own after that.
@Tomalak It's not that self-explanatory, IMHO. And it deserves a downvote partly for what ppeterka mentioned, and partly because ‘code dump’ answers make it seem like it's OK to use SO as a code-writing service. (Again; IMHO (which is what dictates my voting).)
|
2

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);
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.