This class parses/encodes URLs, and provides an interface that parallels the browser’s Location object, except using jQuery style getter/setter methods instead of simple properties.
Note: This class doesn’t support some of the more esoteric features of URLs.
If you need this kind of support, you should use a more robust (and heavyweight) implementation such as
node.js’s Url module.
Usage
####Parse a URL:
varurl=new$.Url("http://www.foo.com:8080/pages/page1.html?key1=value1&key2=value2#someAnchor")url.protocol()==="http";// trueurl.hostname()==="www.foo.com";// trueurl.host()==="www.foo.com:8080";// trueurl.port()==="8080";// trueurl.pathname()==="/pages/page1.html";// trueurl.search()==="?key1=value1&key2=value2";// trueurl.hash()==="#someAnchor";// true// The queryString property is a simple parsed object which contains key value pairs.url.queryString.key1==="value1";// trueurl.queryString.key2==="value2";// true
####Manipulating the querystring
Once the URL is parsed, you can manipulate the querystring:
// Adds a parameter, or overwrites one if it already existsurl.set("key3","value3")// Gets the value of an existing parametervarkey1Value=url.get("key1")// Gets the value of an existing parameter, // specifying a default in case the value doesn't existvarkey1Value=url.get("key1","some default value")// Removes a parameterurl.remove("key3")
Serializing back to a URL string
The toString() method of $.Url will write back to a string: