How to get the URL without any parameters in JavaScript?

前端 未结 9 1496
终归单人心
终归单人心 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:32

    I'm LATE to the party, but I had to solve this recently, figured I'd share the wealth.

    const url = window.location.origin + window.location.pathname
    //http://example.com/somedir/somefile/
    

    window.location.origin will give you the base url, in our test case: http://example.com

    window.location.pathname will give you the route path (after the base url), in our test case /somedir/somefile

    SOLUTION 2

    You can simply do the following to get rid of the query parameters.

    const url = window.location.href.split('?')[0]

提交回复
热议问题