David542 David542 - 1 year ago 103
Javascript Question

Javascript get url without querystring

I have the following url:

url = 'http://stackoverflow.com/questions/ask?new=question'

How would I get the url without the querystring? Right, now I am doing the following, but is there a single method to do this instead of adding two?

window.location.origin + window.location.pathname

Answer Source

To get all the different parts of a url, location.protocol + '//' + location.host + location.pathname would be the correct syntax. Here's an example displaying the url where this snippet is hosted:

document.body.innerHTML = "The snippet is at this web address: " + getURL();

function getURL() {
  return location.protocol + '//' + location.host + location.pathname

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download