5

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.

rodneyrehm
  • 13,442
  • 1
  • 40
  • 56
  • possible duplicate of [How do I parse a URL into hostname and path in javascript?](http://stackoverflow.com/questions/736513/how-do-i-parse-a-url-into-hostname-and-path-in-javascript) – Cameron Dec 20 '11 at 17:35
  • @Cameron The questions may be similar, but the library that I linked to isn't there for example (and maybe other solutions as well). – deviousdodo Dec 20 '11 at 17:37
  • @draevor: Yep, might be best to keep both (or have them merged, maybe). – Cameron Dec 20 '11 at 17:47
  • Something made from scratch: http://jsfiddle.net/u7BD8/1/. Surely contains some bugs but it may be usable. – pimvdb Dec 20 '11 at 17:56
  • I'm not asking how to parse an URL. I was asking if there is a standard API I didn't know yet, or at least an opinion on some "standard" library to use. – rodneyrehm Dec 20 '11 at 20:59

2 Answers2

3

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
roberkules
  • 6,557
  • 2
  • 44
  • 52
2

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 :)

rodneyrehm
  • 13,442
  • 1
  • 40
  • 56