URL management?

Is there a (native) javascript API that offers window.location "functionality" for custom URLs? something along the lines

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"

I'm sure there is no native API for this (for whatever reason ever). If someone has done this, please share the link.

+5
source share
2 answers

So the answer is yes and no.

As follows from some answer, you can create a binding element and use it for parsing, which is mainly internal code.

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"

Live demo: http://jsfiddle.net/roberkules/H48dt/

The only difference is that ? not deleted after freeing the query string.

"API":

url.protocol
url.host
url.port
url.pathname
url.search
url.hash
+3

URL- API, : URI.js.

/ URL- jQuery- API , URL- / .

, :)

+2

All Articles