Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...