简体   繁体   中英

How to get url path without $_GET parameters using javascript?

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?

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 )

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

try this:

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

Try

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

Working demo

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;
   }, {});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM