5

If my current page is in this format...

http://www.mydomain.com/folder/mypage.php?param=value

Is there an easy way to get this

http://www.mydomain.com/folder/mypage.php

using javascript?

5 Answers 5

6

Don't do this regex and splitting stuff. Use the browser's built-in URL parser.

window.location.origin + window.location.pathname

And if you need to parse a URL that isn't the current page:

var url = document.createElement('a');
url.href = "http://www.example.com/some/path?name=value#anchor";
console.log(url.origin + url.pathname);

And to support IE (because IE doesn't have location.origin):

location.protocol + '//' + location.host + location.pathname;

(Inspiration from https://stackoverflow.com/a/6168370/711902)

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

2 Comments

I have to agree, this accomplishes exactly what I needed without any unnecessary steps. Thank you.
this doesn't work in Opera 12 (and earlier) and in IE (w3schools.com/jsref/prop_loc_origin.asp)
3

Try to use split like

var url = "http://www.mydomain.com/folder/mypage.php?param=value";
var url_array = url.split("?");
alert(url_array[0]);    //Alerts http://www.mydomain.com/folder/mypage.php

Even we have many parameters in the GET , the first segment will be the URL without GET parameters.

This is DEMO

2 Comments

Thank you, just what I needed! I did not mention it in the question, but this also works when no parameters are passed =)
How would your string-based solution handle a malformed URL, such as http://www.domain.com/page#anchor?parameter ? Using the document object and it's api is a more robust solution IMO
2

try this:

var url=document.location.href;
var mainurl=url.split("?");
alert(mainurl[0]);

Comments

0

Try

var result = yourUrl.substring(0, yourUrl.indexOf('?'));

Working demo

Comments

0
var options = decodeURIComponent(window.location.search.slice(1))
     .split('&')
     .reduce(function _reduce (/*Object*/ a, /*String*/ b) {
     b = b.split('=');
     a[b[0]] = b[1];
     return a;
   }, {});

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.