Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

window.location.href or window.location.search

Tags:

javascript

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

like image 945
MockedMan.Object Avatar asked Jan 02 '16 09:01

MockedMan.Object


People also ask

What can I use instead of window location href?

Location assign() Method location. replace("http://someUrl.com");

What is difference between window location or location?

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.


3 Answers

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.

like image 77
Darin Dimitrov Avatar answered Oct 13 '22 08:10

Darin Dimitrov


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);
like image 28
hossein sedighian Avatar answered Oct 13 '22 08:10

hossein sedighian


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')
like image 44
Kieran Pilkington Avatar answered Oct 13 '22 07:10

Kieran Pilkington