parseUri 1.2: Split URLs in JavaScript

I've just updated parseUri. If you haven't seen the older version, parseUri is a function which splits any well-formed URI into its parts, all of which are optional. Its combination of accuracy, flexibility, and brevity is unrivaled.

Highlights:

  • Comprehensively splits URIs, including splitting the query string into key/value pairs. (Enhanced)
  • Two parsing modes: loose and strict. (New)
  • Easy to use (returns an object, so you can do, e.g., parseUri(uri).anchor).
  • Offers convenient, pre-concatenated components (path = directory and file; authority = userInfo, host, and port; etc.)
  • Change the default names of URI parts without editing the function, by updating parseUri.options.key. (New)
  • Exceptionally lightweight (1 KB before minification or gzipping).
  • Released under the MIT License.

Details:

Older versions of this function used what's now called loose parsing mode (which is still the default in this version). Loose mode deviates slightly from the official generic URI spec (RFC 3986), but by doing so allows the function to split URIs in a way that most end users would expect intuitively. However, the finer details of loose mode preclude it from properly handling relative paths which do not start from root (e.g., "../file.html" or "dir/file.html"). On the other hand, strict mode attempts to split URIs according to RFC 3986. Specifically, in loose mode, directories don't need to end with a slash (e.g., the "dir" in "/dir?query" is treated as a directory rather than a file name), and the URI can start with an authority without being preceded by "//" (which means that the "yahoo.com" in "yahoo.com/search/" is treated as the host, rather than part of the directory path).

Since I've assumed that most developers will consistently want to use one mode or the other, the parsing mode is not specified as an argument when running parseUri, but rather as a property of the parseUri function itself. Simply run the following line of code to switch to strict mode:

parseUri.options.strictMode = true;

From that point forward, parseUri will work in strict mode (until you turn it back off).

The code:

// parseUri 1.2.2
// (c) Steven Levithan <stevenlevithan.com>
// MIT License

function parseUri (str) {
	var	o   = parseUri.options,
		m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
		uri = {},
		i   = 14;

	while (i--) uri[o.key[i]] = m[i] || "";

	uri[o.q.name] = {};
	uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
		if ($1) uri[o.q.name][$1] = $2;
	});

	return uri;
};

parseUri.options = {
	strictMode: false,
	key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
	q:   {
		name:   "queryKey",
		parser: /(?:^|&)([^&=]*)=?([^&]*)/g
	},
	parser: {
		strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
		loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
	}
};

You can download it here.

parseUri has no dependencies, and has been tested in IE 5.5–7, Firefox 2.0.0.4, Opera 9.21, Safari 3.0.1 beta for Windows, and Swift 0.2.

173 thoughts on “parseUri 1.2: Split URLs in JavaScript”

  1. Ensure outfits dryers are vented outside of the basement, perhaps not
    inside. It is a slimy greenish-black material, which may develop in humid environments.
    A top level diabetic person, you’re verey prone to attacks.

  2. Anaconda is at 5,280 feet – Montana’s mile-high city,flanked mountains, lakes and fields.
    Perhaps you have been struggling since the bubble broke open.

    Solar panels power abilities range from watts to kilowatts.

  3. This makws your future financial planning easy and may
    reduce the strain. Debt settlement is the best option iff you want to dramatically lessen your outstanding
    costs. Singapore can be among the nagions which can be under debt anxiety.

    Nevertheless, treasury bills aren’t a psrt of the plan.

    Study the utmost effective customers of Structured Settlements.

  4. This cause you need to use proper training so available the drivers license.
    A career in this particular industry implies that no two work days are drinks ..

  5. I was suggested this web site by way of my cousin.

    I’m now not positive whether or not this publish is written through
    him as nobody else recognise such detailed about my difficulty.
    You are wonderful! Thank you!

  6. Ron Lewis scored 9 points, going 7 oof 8 in the free-throw line.

    Nonetheless, these foprm of events will noot
    reaqlly direct you towards the college basketball recruiting process.

    There’s clear and indisputable proof of that.

  7. I am really enjoying the theme/design of your
    web site. Do you ever run into any web browser compatibility issues?
    A couple of my blog visitors have complained about my site not working correctly
    in Explorer but looks great in Opera. Do you have any ideas to help fix this issue?

  8. I’m not that much of a internet reader to be honest but your sites really nice, keep it up!
    I’ll go ahead and bookmark your website to come back
    in the future. All the best

  9. Now I am going away to do my breakfast, afterward having my breakfast coming again to read additional news.

  10. The totally free natural website traffic from search engines like yahoo is a worthwhile asset for any organization that makes use of
    the word wide web. Mso – Normal – Table mso-style-name:”Table Normal”; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:
    0; mso-style-noshow:yes; mso-style-priority:99; mso-style-qformat:
    yes; mso-style-parent:””; mso-padding-alt:0in 5. Your healthcare web developments have to encompass trust at their heart.

  11. Of course, to get a complete setup you would
    also need the site to be developed. It is
    also helpful to arouse energy and motivate interest.
    In today’s day and age, people are quite passionate about online shopping and are increasingly choosing this option for most of their purchases.

  12. Thanks for the marvelous posting! I quite enjoyed reading it, you can be a great author.I will remember to bookmark your blog
    and will eventually come back in the foreseeable future.
    I want to encourage continue your great writing, have a nice evening!

  13. It was put to use when medieval guilds were set-up,
    but not created for turn a profit. You want a lawyer with a background in protecting fraud cases.

  14. J?zyk, jak z trudem czasem zrozumieniu prawni, us?ugi prawach prawa u do?u k?tem jego zrozumie?, co odpowiednio danym terenie tego, którym pos?ugi prawach prawnych
    za? dwadzie?cia cztery godziny. Jej jednym spo?ród zada? jest, a?eby zaznajomi?
    si? na co a? do naszego ich poznaniu. powsta? nawet nadzwyczajny agenda nawet
    specjalistyce. Bada kobieta j?zykiem prawa u do?u k?tem jego odr?bno?ci? udzieli wspomagaj?cy radca
    prawa. Gabinet windykacyjna, obs?uga prawa.
    Artykulacja po tej stronie o juryslingwistyce. Bada
    dama j?zyczno?? za? multikulturalnego, jakim s?u?ba prawa tudzie? tu w?a?ciwie danym terenie stwarza dodatkowe problemy w zrozumienia, wskazane
    jest poprawienie tudzie? t?dy przed momentem prawnicy nagminnie musz? zmierza.

  15. Hi, I think your blog might be having browser
    compatibility issues. When I look at your website
    in Opera, it looks fine but when opening in Internet Explorer, it has some
    overlapping. I just wanted to give you a quick heads up!
    Other then that, awesome blog!

  16. Veteran home-buyers understand that most residences have something that must be restored.
    Antonio is really a son who love to share his knowledge about home business.
    It can be daunting to first time home-buyers.

  17. Building your custom desire house style doesn’t
    have to be a chore or filled with doubt and uncertainty.
    The world leader in record house style is clearly, believe it or
    not, Finland!

  18. Besides, hands on knowledge is vital whilst the objectives
    of consumers are becoming higher and higher. The concept never really occurred
    in my experience. The sheepskins are another distinctive decor in your home accessories.

Leave a Reply

Your email address will not be published. Required fields are marked *