Javascript 如何在javascript中拆分url以获取url路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39334400/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to split url to get url path in javascript
提问by nCore
I have constructed a url path that are pointing to different hostname www.mysite.com
, so for example
我已经构建了一个指向不同主机名的 url 路径,www.mysite.com
例如
var myMainSite = 'www.mymainsite.com' + '/somepath';
so this is equivalent to www.mymainsite.com/path/path/needthispath/somepath
.
所以这相当于www.mymainsite.com/path/path/needthispath/somepath
.
How I'm doing it now is like the code below and this gives me a bunch of indexes of the url in the console.log.
我现在的做法就像下面的代码,这在console.log 中给了我一堆url 的索引。
var splitUrl = myMainSite.split('/');
console.log looks like:
console.log 看起来像:
0: http://
1: www.
2: mysite.com
3: path
4: path
5: needthispath
6: somepath
and I concat them like splitUrl[5]+'/'+splitUrl[6]
and it doesn't look pretty at all.
我把它们连起来splitUrl[5]+'/'+splitUrl[6]
,看起来一点也不漂亮。
So my question is how to split/remove url location http://www.mymainsite.com/
to get the url path needthispath/somepath
in js? Is there an quicker and cleaner way of doing this?
所以我的问题是如何拆分/删除 url 位置http://www.mymainsite.com/
以获取needthispath/somepath
js 中的 url 路径?有没有更快更干净的方法来做到这一点?
回答by Inanc Gumus
First solution (URL object)
第一个解决方案(URL 对象)
The URL objectcan be used for parsing, constructing, normalizing, encoding URLs, and so on.
的URL对象可用于解析,构建,正火,编码的URL,等等。
var url = 'http://www.mymainsite.com/somepath/path2/path3/path4';
var pathname = new URL(url).pathname;
console.log(pathname);
The URL interface represents an object providing static methods used for creating object URLs.
URL 接口表示一个对象,提供用于创建对象 URL 的静态方法。
The Browser supportis pretty good in 2017 (~ 90% but not IE11 nor below)
该浏览器支持是在2017年相当不错(〜90%,但不IE11也没有下文)
Second solution (a kind of a hack)
第二种解决方案(一种黑客)
var urlHack = document.createElement('a');
urlHack.href = 'http://www.mymainsite.com/somepath/path2/path3/path4';
console.log(urlHack.pathname);
// you can even call this object with these properties:
// protocol, host, hostname, port, pathname, hash, search, origin
回答by The Gav Lad
Why don't you use the split function and work from there. The split function will break your URL out fully and from there you just need to look for the second last and last items.
为什么不使用 split 功能并从那里开始工作。拆分功能将完全拆分您的 URL,从那里您只需要查找倒数第二个和最后一个项目。
Here is an example:
下面是一个例子:
var initial_url = 'http://www.mymainsite.com/path/path/needthispath/somepath';
var url = initial_url .split( '/' );
var updated_url= document.location.hostname + '/' + url[ url.length - 2 ] + '/' + url[ url.length - 1 ];