I’m working on a tool which takes the value parameters in the URL and does a few things with them.
My issue is, I can’t seem to use document.location to show the specific value that I’m after, for example:
www.examplesite.com?yourname=gilgilad
I want to use document.location.search
and put it in a var, I need that var's value to be "gilgilad".
Is this even possible using location.search
?
location.search returns the query portion of a URL including the Question mark (?). This return a string and then we do substring operation on that string. substring(1) means return the string skipping the first character.
Method 1: Using the URLSearchParams Object The URLSearchParams is an interface used to provide methods that can be used to work with an URL. The URL string is first separated to get only the parameters portion of the URL. The split() method is used on the given URL with the “?” separator.
If javascript is enabled, window. location.search is safe to use.
Location: search The search property of the Location interface is a search string, also called a query string ; that is, a USVString containing a '?' followed by the parameters of the URL. Modern browsers provide URLSearchParams and URL.searchParams to make it easy to parse out the parameters from the querystring.
The search property of the Location interface is a search string, also called a query string; that is, a string containing a '?' followed by the parameters of the URL. Modern browsers provide URLSearchParams and URL.searchParams to make it easy to parse out the parameters from the querystring. A string. See implementation notes.
Note that $location. search () without arguments is a getter, which returns an object containing all the query string parameters. $location. search () with arguments is a setter, which will write to the query string. Passing null as the second argument causes the parameter to be removed from the query string.
The search property sets or returns the querystring part of a URL, including the question mark (?). The querystring part is the part of the URL after the question mark (?).
location.search
will return all after question mark including it. So there is universal js to get value of the first parameter (even if url has more parameters):
var desire = location.search.slice(1).split("&")[0].split("=")[1]
Example: let's take url http://example.com?name=jon&country=us
location.search
will be equal to ?name=jon&country=us
.slice(1)
skips the ?
, returning the rest of the string..split("&")[0]
splits it into two strings (name=jon
and
country=us
) and takes first one.split("=")[1]
splits name=jon
into name
and jon
and takes the second one. Done!If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With