Javascript URL管理设施?

Javascript URL管理设施?,javascript,Javascript,是否有(本机)javascript API为自定义URL提供window.location的“功能”?类似于 var url = new URL("http://stackoverflow.com/question?hello=world#foo"); console.log(url.hostname, url.path); // out: "stackoverflow.com", "/question" url.hash = "bar"; url.query = ""; console.log

是否有(本机)javascript API为自定义URL提供window.location的“功能”?类似于

var url = new URL("http://stackoverflow.com/question?hello=world#foo");
console.log(url.hostname, url.path);
// out: "stackoverflow.com", "/question"
url.hash = "bar";
url.query = "";
console.log(url);
// out: "http://stackoverflow.com/question#bar"

我相当肯定没有用于此的本机API(出于什么原因)。如果有人实现了这一点,请共享该链接。

因此答案是肯定和否定

正如一些答案所建议的,您可以创建一个锚元素并使用它进行解析,这基本上是本机代码

var url = document.createElement("A");
url.href = "http://stackoverflow.com/question?hello=world#foo";

console.log('// expected: "stackoverflow.com", "/question"');
console.log('//      got: "' + url.hostname + '", "' + url.pathname + '"');
output -->           got: "stackoverflow.com", "/question"

url.hash = "bar";
url.search = "";

console.log('// expected: "http://stackoverflow.com/question#bar"');
console.log('//      got: "' + url.href + '"');
output -->           got: "http://stackoverflow.com/question?#bar"
现场演示:

唯一的区别是,在querystring清空后不会被删除

“API”:


由于没有用于处理URL的有用API,我自己构建了一个:

它允许您通过类似jQuery的API读取/写入URL的组件,并具有一些有用的功能,用于处理查询字符串、规范URL和创建相对/绝对路径


圣诞快乐,享受:)

可能重复@Cameron的问题可能类似,但我链接到的库不在那里(可能还有其他解决方案)。@draevor:是的,可能最好保留这两个库(或者合并它们)。从头开始的东西:。当然包含一些bug,但它可能是可用的。我不是问如何解析URL。我在问是否有一个我还不知道的标准API,或者至少对一些“标准”库有什么看法。我不知道这是可能的,谢谢。(不过帮不了什么忙)
url.protocol
url.host
url.port
url.pathname
url.search
url.hash