URL管理工具?

rod*_*ehm 5 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(url);
// out: "http://stackoverflow.com/question#bar"
Run Code Online (Sandbox Code Playgroud)

我相当确定没有本地API(出于什么原因).如果有人实现了此功能,请分享链接.

rob*_*les 3

所以答案是肯定和否定。

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

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"
Run Code Online (Sandbox Code Playgroud)

现场演示: http: //jsfiddle.net/rorkules/H48dt/

唯一的区别是,? 查询字符串清空后不会被删除。

“API”:

url.protocol
url.host
url.port
url.pathname
url.search
url.hash
Run Code Online (Sandbox Code Playgroud)