I have a link in my collection page on a shopify store.
the link does look like this:
/collections/all?filter.p.tag=animal
I want to grab current active Filters and print it again under the H1 Heading.
But i HAVE TO grab only everything after "tag="
So ignore the rest of the URL and also anything coming from things like "sort_by" or "?fbclid=IwAR2didTPblablabla"
So just everything after "tag="
How this can be done?
CodePudding user response:
Just to give a more fullfilling answer using URLSearchParams:
const paramsString = "?filter.p.tag=animal";
const searchParams = new URLSearchParams(paramsString);
console.log(searchParams.get('filter.p.tag'))
// result: animal
This will get the value from the filter.p.tag
param eg animal
.
Meaning if the url looks something like this:
const paramsString = "?filter.p.tag=animal&sort_by=type";
it will still only return animal
.
If you truly want "everything after "tag="", please see some of the other answers.
Edit: URLSearchParams' argument must be in the right format (eg.: ?some=thing
), so previously I answered it with:
const paramsString = "/collections/all?filter.p.tag=animal";
...
which is incorrect. Only the actual search params string works in URLSearchParams.
To get the correct params string from the URL use location.search
:
const searchParams = new URLSearchParams(location.search);
console.log(searchParams.get('filter.p.tag'))
Sorry for any confusion.
CodePudding user response:
You could get the URL, parse it and keep the parts you care about.
CodePudding user response:
window.location.href will give you the current URL in your web browser.
Then by using the split function with the argument "tag=" you split the string into 2 parts. You get an array back with the first value being the part up to tag=, and the second part is everything after tag=.
window.location.href.split("tag=")[1]
CodePudding user response:
There are a few ways to do it using JavaScript. Here are two options:
Option 1, use the string split method
To get the search parameters of the URL, you can use something like document.location.search
, which evaluates to everything after the "?" in the URL.
Then, you can split the string on "tag=" to get everything after "tag=".
Example code:
const searchParams = document.location.search; // 'filter.p.tag=animal'
const splitString = searchParams.split('tag=');
const everythingAfterTag = splitString[1]; // 'animal'
Option 2, use the URL object constructor
Here is a code example:
const url = document.location.href; // get the entire URL string
const urlObject = new URL(url);
const valueOfTag = urlObject.searchParams.get('filter.p.tag'); // 'animal'