使用JavaScript拆分url

使用JavaScript拆分url,javascript,Javascript,我正在尝试拆分以下url: http://www.store.com/products.aspx/Books/The-happy-donkey 为了只获取http://www.store.com/products.aspx 我正在使用JavaScriptwindow.location.href和split,但到目前为止还没有成功 如何做到这一点?谢谢 试试这个 var fullurl = "http://www.store.com/products.aspx/Books/The-happy-d

我正在尝试拆分以下url:

http://www.store.com/products.aspx/Books/The-happy-donkey
为了只获取
http://www.store.com/products.aspx

我正在使用JavaScript
window.location.href
split
,但到目前为止还没有成功

如何做到这一点?谢谢

试试这个

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

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

这不是很笨拙,是吗

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

[
    url.split('://')[0] + '://', 
    url.split('://')[1].split('/').slice(0,2).join('/')
].join('')
有点不那么厚颜无耻:

url.split('/').slice(0, 4).join('/')
最好的答案(比split)可能是诚实地使用正则表达式,除非你真的需要使用split(为了好玩):

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


但最重要的是,对于一个特定的问题,这不是一个很好的解决策略(尝试更一般地解决类似的问题)。

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

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

首先看看这个问题,它可能对你有帮助,是吗?它是专门针对url的,还是你打算一般地使用这个函数。。。如中所示,如果只删除“/Books/thehappy驴”部分会怎么样?“/Books/thehappy驴”是动态的,因此我唯一的参考是.aspx部分,但使用split时不做任何操作good@GlenSwift实际上没有。。。我需要整个页面直到.aspx,这样我才能连接到webMethod:(嗨,我发现很难理解你的问题,你介意添加更多的输入和预期输出吗?很难从一个这样描述的示例中归纳出来。聪明而有效
console.log(new URL(document.URL));