I have a link on my collection page on a Shopify store.
the link does look like this:
/collections/all?filter.p.tag=animal
I want to grab the current active Filters and print them 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?
5
Answers
You could get the URL, parse it and keep the parts you care about.
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=.
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:
Option 2, use the URL object constructor
Here is a code example:
Just to give a more fullfilling answer using URLSearchParams:
This will get the value from the
filter.p.tag
param eganimal
.Meaning if the url looks something like this:
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:which is incorrect. Only the actual search params string works in URLSearchParams.
To get the correct params string from the URL use
location.search
:Sorry for any confusion.