简体   繁体   中英

How to get the URL without any parameters in JavaScript?

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:

http://mysite.com/somedir/somefile/

instead of

http://mysite.com/somedir/somefile/?foo=bar&loo=goo

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

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

Every answer is rather convoluted. Here:

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

Even if a? isn't present, it'll still return the first argument, which will be your full URL, minus query string.

It's also protocol-agnostic, meaning you could even use it for things like ftp, itunes.etc.

Use indexOf

var url = "http://mysite.com/somedir/somefile/?aa";

if (url.indexOf("?")>-1){
url = url.substr(0,url.indexOf("?"));
}

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]

You can concat origin and pathname , if theres present a port such as example.com:80 , that will be included as well.

location.origin + location.pathname
var url = "tp://mysite.com/somedir/somefile/?foo=bar&loo=goo"    

url.substring(0,url.indexOf("?"));

You can use a regular expression: window.location.href.match(/^[^\#\?]+/)[0]

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

If you look at the documentation you can take just the properties you're interested in from the window object ie

protocol + '//' + hostname + pathname

Use the URL() constructor, then extract and concatenate the origin and pathname. This will automatically strip the search (aka query) parameters from the url, leaving the scheme, domain, port and pathname only.

 const url = new URL('http://localhost:8080/index.html?search=foo&other=bar'); console.log(url.origin + url.pathname);

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