OhReallyJS


script-url.js

Synopsis

This script will turn any given URL into a JavaScript object, making it easy to analyse and change the URL.
The properties of the created object mimic the properties of window.location (http://www.w3schools.com/js/js_window_location.asp), and a few properties and methods are added.

urlObject does not try to replace window.location.
These are the differences:

This script does not validate or correct any values. (That's your job.)

License

Copyright © 2016 Rob la Lau <https://ohreally.nl/>

This work is licensed under a Creative Commons Attribution 4.0 International License (https://creativecommons.org/licenses/by/4.0/deed.en).

Please be aware that minimizing this script does not mean that you don't have to include the copyright and author info.

Download

After reading the license information, you can download the current version of script-url.js by clicking → heregoing to https://js.ohreally.nl/download/script-url.js

Please, host the script with your own website instead of linking to the scripts at js.ohreally.nl directly.
Read thisRead https://js.ohreally.nl/hiy if you want to know why.

Dependencies

This script does not depend on any other scripts.

See Browser compatibility below for the list of supported/supporting browsers.

Installation

Save the script to the root of your website (http://www.example.com/script-url.js), and add this line to the <head/> section of your webpages:

<script type="text/javascript" src="/script-url.js"></script>

Usage

Create a urlObject by passing a URL to the constructor:

var myUrl = new urlObject('http://www.example.com/path/to/page.html?x=1&y=2');

The URL is optional:

var myUrl = new urlObject();

is the same as

var myUrl = new urlObject(window.location.href);

See also the examples below.

Properties

The returned object has the following properties:

myUrl.href
mimics window.location.href: sets or gets the entire URL
see also myUrl.toString(); this property returns the same value as myUrl.toString(false)
myUrl.protocol
mimics window.location.protocol: sets or gets the protocol (e.g. http:)
myUrl.scheme
like myUrl.protocol, but without the colon ( : )
myUrl.username
sets or gets the username *
myUrl.password
sets or gets the password *
myUrl.credentials
sets or gets the username and password, separated by a colon ( : ); when getting, the credentials are followed by an at-sign ( @ ) *
myUrl.hostname
mimics window.location.hostname: sets or gets the hostname
myUrl.port
mimics window.location.port: sets or gets the port number; when getting, if the port number is the default port for the scheme, the empty string is returned
myUrl.host
mimics window.location.host: sets or gets the host (hostname with optional port number, separated by a colon ( : )
myUrl.origin
mimics window.location.origin (but is writable): sets or gets the origin ( scheme://host )
myUrl.pathname
mimics window.location.pathname: sets or gets the path (e.g. /path/to/document.html)
mimics window.location.search: sets or gets the querystring (e.g. ?x=1&y=2)
see also myUrl.getQueryParam() and myUrl.setQueryParam()
myUrl.query
like myUrl.search, but without the question mark ( ? )
see also myUrl.getQueryParam() and myUrl.setQueryParam()
myUrl.querySeparator
the string to be used to separate querystring parameters
accepted values are & (alias: js) and &amp; (alias: html, xhtml or xml) **
myUrl.hash
mimics window.location.hash: sets or gets the anchor (e.g. #section)
myUrl.fragment
like myUrl.hash but without the number sign ( # )
myUrl.guessMissing
may be true or false; defaults to false
if set to true, missing values are 'guessed':
- missing scheme is filled in by looking at the port number, or, if that is also missing, by copying from myUrl.guessBase
- missing hostname is copied from myUrl.guessBase
- missing pathname is set to the pathname of myUrl.guessBase if myUrl.search/myUrl.query and/or myUrl.hash/myUrl.fragment is/are set, or / otherwise
these 'guessed' values are filled in when getting the values; they do not change the URL in the object
myUrl.guessBase
sets or gets the URL that serves as the base URL for values that should be 'guessed' (see myUrl.guessMissing)
this defaults to window.location.href

Methods

The returned object has the following methods:

myUrl.toString([guess])
returns the entire URL as a string
the optional parameter may be true or false, and determines whether missing values are 'guessed'; this defaults to false, and overrides, but does not set, the guessMissing property
myUrl.getQueryParam(key)
- returns the value for the given querystring parameter ( ?param=value )
- returns true if the parameter was set without a value ( ?param )
- returns the empty string if the parameter was set with an empty value ( ?param= )
- returns false if the parameter was not set
myUrl.setQueryParam(key, value, overwrite)
- sets the given querystring parameter ( key ) to the given value
- the optional 3rd parameter may be true or false, and determines whether an existing parameter with this key should be overwritten; this defaults to false
- if value is true, sets the parameter without a value
- if value is false, deletes the given parameter, if it exists (this implies overwrite is true)
- if key contains square brackets ( [] ), an array will be created (and returned by the getQueryParam() method)
- if key contains square brackets ( [] ), and a string parameter with the same name exists, an array is created with the string as it's first value
- if key contains square brackets ( [] ), and an array with that name already exists, and overwrite is false, the key-value pair will be appended to the array
- if key contains square brackets ( [] ), and an array with that name already exists, and overwrite is true, the existing array will be deleted, and a new array with that name will be created
- multidimensional arrays are not (yet) supported

Notes:

*
For security reasons, authentication information in URLs is considered deprecated (see RFC7230, section 2.7.1).
**
In JavaScript, querystring parameters are separated by &. In HTML and XML, querystring parameters are separated by &amp;. This script has no way of knowing whether a URL comes from JavaScript (e.g. window.location.href) or from HTML/XML (e.g. from reading the href attribute of an <a/> tag).
urlObject tries to deduce the desired separator from the URL it was fed: if the URL has it's querystring parameters separated by &, it will return querystring parameters separated by &, and the same principal goes for &amp;.
The returned separator may be changed by setting the querySeparator property.
If no separator has been set (e.g. urlObject() was fed a URL without querystring, and parameters were added later using the
setQueryParam() method), the separator will default to &.

Examples

var myUrl = new urlObject('http://www.example.com/path/to/page.html?x=1&y=2');

var h = myUrl.hostname;
// h is now 'www.example.com'

var y = myUrl.getQueryParam('y');
// y is now '2'

myUrl.pathname = '/path/to/other.html';
myUrl.setQueryParam('z', '3');
var u = myUrl.toString();
// u is now 'http://www.example.com/path/to/other.html?x=1&y=2&z=3'

myUrl.querySeparator = 'html';
var q = myUrl.query;
// q is now 'x=1&amp;y=2&amp;z=3'

myUrl.scheme = 'https';
var s = myUrl.toString();
// s is now 'https://www.example.com/path/to/other.html?x=1&amp;y=2&amp;z=3'

//---

var newUrl = new urlObject();
newUrl.href = 'http://www.example.com/document.html';
var p = newUrl.pathname;
// p is now '/document.html'

//---

var otherUrl = new urlObject('/path/to/page.html');
otherUrl.guessBase = 'http://www.example.com/some/document.html';
var t = otherUrl.toString(true);
var f = otherUrl.toString();
// t is now 'http://www.example.com/path/to/page.html'
// f is now '/path/to/page.html'

A live example can be found in the source of the contact page (https://js.ohreally.nl/contact), where the subject for the message is selected from the value in the querystring of the page.

Browser compatiblity

Firefox 4.0
Chrome 5
Internet Explorer 9
Opera 11.60
Safari 5

Found a browser that works, but is not listed? Please, let me know (https://js.ohreally.nl/contact).

Bug reports

Don't get your hopes up too high for feature requests (the script already has more features than I need), but if you want to report a bug, feel free to use the contact form (https://js.ohreally.nl/contact).