How to get Indices from pattern matching?

Viewed 40
https://mywebsite/products?category_ids=1&category_ids=3&category_ids=4&category_ids=11&category_ids=10048&category_ids=10785

This is my url with searching patterns. Now I want to filter and get the ids of category_ids

Output should be:

[1, 3, 4, 11, 10048, 10785]
2 Answers

Here's a one-liner:

console.log(new URL('https://mywebsite/products?category_ids=1&category_ids=3&category_ids=4&category_ids=11&category_ids=10048&category_ids=10785').searchParams.getAll('category_ids').map(Number));

References:

You can easily achieve the result using regex as

1)

const url =
  "https://mywebsite/products?category_ids=1&category_ids=3&category_ids=4&category_ids=11&category_ids=10048&category_ids=10785";

const result = url
  .split("?")[1]
  .match(/(?<==)\d+/g)
  .map(Number);
console.log(result);

2)

const url =
  "https://mywebsite/products?category_ids=1&category_ids=3&category_ids=4&category_ids=11&category_ids=10048&category_ids=10785";

const result = url
  .split("?")[1]
  .match(/=\d+/g)
  .map((s) => +s.slice(1));
console.log(result);

Related