有没有一个(原生的) 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来实现这一点(无论出于什么原因)。如果有人实现了这一点,请分享链接。
发布于 2011-12-22 12:55:42
所以答案是肯定的,也可能不是。
正如一些答案所建议的那样,您可以创建一个锚元素并使用它来执行解析,这基本上是本机代码。
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"现场演示:http://jsfiddle.net/roberkules/H48dt/
唯一的区别是,在清空查询字符串之后,不会被删除。
接口:
url.protocol
url.host
url.port
url.pathname
url.search
url.hash发布于 2011-12-27 19:14:33
由于没有用于处理URL的有用应用程序接口,我自己构建了一个:URI.js。
它允许您通过类似jQuery的API读/写URL的组件,并具有一些有用的功能,用于处理查询字符串、规范化URL和创建相对/绝对路径。
圣诞快乐,祝你愉快:)
https://stackoverflow.com/questions/8579453
复制相似问题