I want to extract out the query string values from the URL.
So, in the most upvoted answer in How can I get query string values in JavaScript? - window.location.search
is used.
Is there any problem in using window.location.href
?
I am trying to root cause a problem where in sometimes I am getting empty query string value when using location.href
Location assign() Method location. replace("http://someUrl.com");
window. location is an object that holds all the information about the current document location (host, href, port, protocol etc.). location. href is shorthand for window.
The 2 properties return different things
:
href: Is a DOMString containing the whole URL.
and:
search: Is a DOMString containing a '?' followed by the parameters of the URL. Also known as "querystring"
So you could use one or the other, just make sure to account for the differences between the returned values in your function. If you decide to use the href
property you will need to first extract the query string part (the part after the ?
) before splitting it into pieces.
i use
var qr={};
window.location.search.substring(1).split("&").forEach(p => { qr[p.split("=")[0]] = p.split("=")[1] })
//use
console.log(qr["sample"]);
//or
console.log(qr.sample);
Browsers now have a URLSearchParams class that can help to parse search params. It has been around in modern browsers for almost 4 years now: https://caniuse.com/?search=URLSearchParams
let queryParams = new URLSearchParams(window.location.search)
queryParams.set('page', '1')
queryParams.toString()
queryParams.get('page')
queryParams.delete('page')
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