Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URL management facility?

Tags:

javascript

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

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 fairly certain there is no native API for this (for what reason ever). If someone implemented this, please share the link.

like image 387
rodneyrehm Avatar asked Dec 20 '11 17:12

rodneyrehm


2 Answers

So the answer would be yes and no.

As some answer suggests, you could create an anchor element and use it to do the parsing, which is basically native 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 the ? is not removed after the querystring is emptied.

The "API":

url.protocol
url.host
url.port
url.pathname
url.search
url.hash
like image 164
roberkules Avatar answered Sep 24 '22 21:09

roberkules


Since there was no useful API for working with URLs, I built one myself: URI.js.

It allows you to read/write components of an URL via a jQuery-like API and has some useful features for working with query strings, normalizing URLs and creating relative/absolute paths.

Merry Christmas, enjoy :)

like image 32
rodneyrehm Avatar answered Sep 20 '22 21:09

rodneyrehm