使用 javascript 拆分 url

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15538435/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 01:07:32  来源:igfitidea点击:

Split url with javascript

javascript

提问by Arturo Suarez

I'm trying to split following url:

我正在尝试拆分以下网址:

http://www.store.com/products.aspx/Books/The-happy-donkey

http://www.store.com/products.aspx/Books/The-happy-donkey

in order to get only http://www.store.com/products.aspx

为了只获得http://www.store.com/products.aspx

I'm using javascript window.location.href and split but not success so far. How can this be done? thanks

我正在使用 javascript window.location.href 和 split 但到目前为止还没有成功。如何才能做到这一点?谢谢

采纳答案by Sasidhar Vanga

Try this

试试这个

var fullurl = "http://www.store.com/products.aspx/Books/The-happy-donkey",
    url = fullurl.split(".aspx")[0] + ".aspx";

回答by Daniel

In the case of a url: http://www.store.com/products.aspx/Books/The-happy-donkeyfrom the address bar

在网址的情况下:http://www.store.com/products.aspx/Books/The-happy-donkey来自地址栏

 var path = window.location.pathname;
 var str = path.split("/");
 var url = document.location.protocol + "//" + document.location.hostname + "/" + str[1];

回答by Jared Farrish

This isn't unwieldy, is it?

这并不笨拙,是吗?

var url = 'http://www.store.com/products.aspx/Books/The-happy-donkey';

[
    url.split('://')[0] + '://', 
    url.split('://')[1].split('/').slice(0,2).join('/')
].join('')

A little less cheeky:

少一点厚脸皮:

url.split('/').slice(0, 4).join('/')

回答by Ryan

The better answer (than split) is probably with a regex honestly unless you just REALLY need to use split (for the fun of it):

老实说,更好的答案(比 split 更好)可能是使用正则表达式,除非您真的需要使用 split (为了它的乐趣):

var shorterUrl = window.location.href.replace(/\.aspx.+/gi, ".aspx");

this replaces the end of your given url, starting at .aspx and just keeps the .aspx part.

这将替换给定 url 的末尾,从 .aspx 开始,只保留 .aspx 部分。

But foremost, this is not a good solution tactic to a specific problem (try to solve problems like this more generically).

但最重要的是,这不是解决特定问题的好策略(尝试更通用地解决此类问题)。

回答by robby dwi hartanto

try this, you would get object of url

试试这个,你会得到 url 的对象

console.log(new URL(document.URL));

控制台日志(新 URL(文档.URL));