0

suppose that, i've this string:

google.com/:id/:category

how can i extract only id and category from this string?

i should use regex

this match doesn't work:

match(/\/:([a-zA-Z0-9]*)/g);

2
  • Explain why it doesn't work, because it should work. Commented Mar 7, 2022 at 12:19
  • because response is: (2) ['/:id', '/:category'] but i need ['id', category] Commented Mar 7, 2022 at 12:20

2 Answers 2

8

You may try the following:

var url = "google.com/:id/:category";
var parts = url.match(/(?<=\/:)[a-zA-Z0-9]+/g);
console.log(parts);

This approach uses the positive lookbehind (?<=\/:) to get around the problem of matching the unwanted leading /: portion. Instead, this leading marker is asserted but not matched in the version above.

Sign up to request clarification or add additional context in comments.

Comments

2

Well, capture groups are ignored in match with /g. You might go with matchAll like this:

const url = "google.com/:id/:category"
const info = [...url.matchAll(/\/:([a-zA-Z0-9]*)/g)].map(match => match[1])
console.log(info)

Credit: Better access to capturing groups (than String.prototype.match())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.