How to get a string within a string (JS)
Let's say for example, I have the following string in a URL
/?search_query=new%shoes&filter=shirts&color=red
or
/?filter=jackets&search_query=new%shoes&color=orange
or any other combination. What's the best approach at pulling only the search_query value from the string?
search_query=new%shoes would result in 'New Shoes'.
I need to do this dynamically to account for any size string and any order. I was thinking of using substring and trying to find the nearest index of say = and & or & and (nothing), if there is a case where URL is just /?search_query=new%shoes
7 Replies
I might be explaining this horribly, but the goal is to create a search bar that works with filtering functions for a catalog. Right now I'm trying to pull the user's query in order to display as the input's placeholder after they search
you're query is wrong - it should be
new%20shoes
which would yield new shoes
. If you need it capitalized you could handle that in the URL or you could do that with CSS text-transform: capitalize;
Next, you can get the URL params from window.location.search
and assign that to a variable: const queryString = window.location.search
From there, you can do like const urlParams = new URLSearchParams(queryString)
From there you can do like urlParams.get("search_query")
which would return new shoes
Here's more docs on URLSearchParams
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/getMDN Web Docs
URLSearchParams: get() method - Web APIs | MDN
The get() method of the URLSearchParams
interface returns the first value associated to the given search parameter.
Thank you, I was oblivious to this approach
I actually just finishing making a solution doing nothing close to this. I'm still new to JS but this is what I came up with 😅
That kinda would work unless you have other special characters like an apostrophe which would be %27, so then it would still show up like Matt%27s New Shoes
I was thinking of adding a condition to check for those 1 off characters separately
URLSearchParams would do all of it for you - and you could actually turn the params into an easy to use object too
something as simple as
the only thing i'd change in your url is to go from
search_query
to one word either search
or query
or even q
which is pretty commonThat's awesome wow. Thank you very much
This has been a complete head ache lol