How to get the URL without any parameters in JavaScript?

前端 未结 9 1429
终归单人心
终归单人心 2020-12-04 09:12

If I use:

alert(window.location.href);

I get everything including query strings. Is there a way to just get the main url part, for example:

相关标签:
9条回答
  • 2020-12-04 09:46

    This is possible, but you'll have to build it manually from the location object:

    location.protocol + '//' + location.host + location.pathname
    
    0 讨论(0)
  • 2020-12-04 09:49

    Use indexOf

    var url = "http://mysite.com/somedir/somefile/?aa";
    
    if (url.indexOf("?")>-1){
    url = url.substr(0,url.indexOf("?"));
    }
    
    0 讨论(0)
  • 2020-12-04 09:50

    Just one more alternative using URL

    var theUrl = new URL(window.location.href);
    theUrl.search = ""; //Remove any params
    theUrl //as URL object
    theUrl.href //as a string
    
    0 讨论(0)
提交回复
热议问题