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?

Neil Harlow
  • 110
  • 2
  • 11

5 Answers5

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)

Community
  • 1
  • 1
Trevor Dixon
  • 23,216
  • 12
  • 72
  • 109
  • I have to agree, this accomplishes exactly what I needed without any unnecessary steps. Thank you. – Neil Harlow Aug 14 '13 at 04:55
  • this doesn't work in Opera 12 (and earlier) and in IE (http://www.w3schools.com/jsref/prop_loc_origin.asp) – Micer Oct 03 '14 at 11:40
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

GautamD31
  • 28,552
  • 10
  • 64
  • 85
  • Thank you, just what I needed! I did not mention it in the question, but this also works when no parameters are passed =) – Neil Harlow Aug 14 '13 at 04:47
  • 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 – Michael Jasper Aug 14 '13 at 04:55
2

try this:

var url=document.location.href;
var mainurl=url.split("?");
alert(mainurl[0]);
Super Hornet
  • 2,839
  • 5
  • 27
  • 55
0

Try

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

Working demo

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
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;
   }, {});
Shemeer M Ali
  • 1,030
  • 15
  • 39