简体   繁体   中英

Current URL without parameters, hash, http(s)://

I'm looking for a neat way of getting the URL of the current document in Javascript.

  • The URL should be clean of parameters (?parameter1=bla&parameter2=bla)
  • The URL should be clean of hash tags (#jumppoint)
  • http/https should be removed/consolidated into http

I know i can get the current URL with location.href and then use some regular expressions to clean it up but maybe there is a nicer/cleaner solution for getting rid of the junk?

There are many other parameters than the href in window.location . See full reference here: https://developer.mozilla.org/en/DOM/window.location

What you are looking for as a starter might be the window.location.hostname :

"the host name (without the port number or square brackets)."

From the example URL http://[www.example.com]:80/search?q=devmo#test the hostname will be www.example.com .

If you also want to include the path and force a http:// protocol, try:

'http://' + window.location.hostname + window.location.pathname;

As a side note, a nifty trick to get the same parameters from another URL than the window.location is to create an empty anchor:

var a = document.createElement('a');
a.href = 'http://www.example.com:80/search?q=devmo#test';

console.log('http://' + a.hostname + a.pathname);

None of the given answers address the fact that the protocol can be http or https as in the OPs title. To accommodate this I suggest:

document.location.protocol +"//"+ document.location.hostname + document.location.pathname

Location对象得到了你需要的东西

window.location.hostname + window.location.pathname

Please try this snippet:

 if (!window.location.origin){ // For IE window.location.origin = window.location.protocol + "//" + (window.location.port ? ':' + window.location.port : ''); } url = window.location.origin + window.location.pathname; document.write('Origin url: ' + url); 

You have document.location object, so:

var oLoc = document.location,
    sUrl = oLoc.protocol + oLoc.hostname;
    // or "http://" + oLoc.hostname

You can use these replacement functions to remove the hash and search arguments and normalize https to http:

url = url.replace(/#[^#]*$/, "").replace(/\?[^\?]*$/, "").replace(/^https:/, "http:");

Or, if all you really want is the domain and path, you can just use this:

window.location.hostname + window.location.pathname

页面表明您可能使用window.location.host来获取您真正感兴趣的部分。但我还没有测试过它。

尝试:


window.location.hostname;

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