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]
CodePudding user response:
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:
CodePudding user response:
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);
CodePudding user response:
Like this:
const urlParams = new URLSearchParams( window.location.search );
console.log( urlParams.getAll( 'category_ids' ) );
However, if you want to use this in e.g. PHP you will run into problems. The GET variable will only contain the last value. If you already know that you are passing array values use ?category_ids[]=1&category_ids[]=2 in your url.
This way you can access them via
const urlParams = new URLSearchParams( window.location.search );
console.log( urlParams.getAll( 'category_ids[]' ) );
and via PHP like this
print_r( $_GET[ 'category_ids' ] );
(or consider using a comma separated list in your url params)