3

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

2 Answers 2

6

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
}

Sign up to request clarification or add additional context in comments.

Comments

5

For example like this - location.href.split("?")[0] - split by ? and take the first element of the resultant array. It will work even if there is no ? in location - the whole url will be the single element of array.

ps: downvoter - comments? don't be a chicken.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.