parseUri 1.2: Split URLs in JavaScript

Edit (2024): parseUri has had a major update and is now available on GitHub and npm

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.

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

  1. @yonathan garti, the easiest way to deal with this is to URL-encode the @ sign as %40. You can see a few people including myself discussing this issue in earlier comments. I plan to correct this in future versions of the script, but haven’t gotten around to it yet. You could try simply changing each instance of [^:@] to [^:@?]. That might do the trick, though I haven’t fully evaluated its impact.

  2. I needed to get the file name and extension so I added this before returning the info in the function.

    var file_pieces = uri[o.key[11]].split(‘.’);
    if ( file_pieces.length > 1 )
    {
    uri.file_ext = file_pieces[file_pieces.length – 1];
    file_pieces.splice(file_pieces.length – 1, 1);
    }
    uri.file_name = file_pieces.join(‘.’);

  3. Hi Steven,
    I have tried replacing [^:@] to [^:@?] in both strict and loose mode and i was able to parse the URL containing @ correctly.

    Thanks for the script.

    –Ramesh

  4. this is sweet, i’m focusing on javascript nowadays and your code amazed me, pretty light and effective. thanks!

  5. Hello,

    Sorry but your code break with this valid flickr url: “http://www.flickr.com/photos/9242564@N07/5934435067/”.

    It has problems with “@” char.

  6. The handling of query strings seems wrong – e.g parse(‘http://example.com/?q=space%20space’).queryKey[‘q’] will return “space%20space”, not “space space” as it ought to be.

    If you’re turning query keys into a parameter map (rather than leaving them as a raw string), both keys and values should be URI-decoded.

  7. Hi Steven,
    thank you for this very helpful script and putting it under MIT license.
    Please consider removing all the spam comments since August 1.
    Looking forward to the next version of parseUri.
    Regards

  8. Use the best website positioning software package to rank to start with on google.
    Maximize your visibility, your rank and your search engine optimization.
    Don’t feel me, test this awesome web optimization computer software for free of charge and see the energy of top quality and
    superior inbound links. Pleased link creating and prepare you to rank bigger and
    receive flood of qualified trafic which really transform.

  9. Ensure clothes dryers are vented outside the basement, perhaps not inside.
    It is a slimy greenish-black material, which can develop in humikd environments.
    A hiugher degree diabetic person, you’re very prone to attacks.

  10. Work wiith a clean washcloth to make the surface dry. Moreover,
    you’ll understand what techniques are ideal for you.
    Temperature can be a typical symptom of an allergy to black mold.

  11. Excess epidermis is a favorite side effect of
    rapid loss in body mass quickly. The experts of this plan suggest you through providing you holistic
    and essential plan. You are lacking to join a fancy gym either.

  12. Both fire damages and water damages are difficult and clear up will be slow.
    The contractor of water damage restoration companies will allow you to get everything out.
    Take any wet books that endd up being in there and layy them out flat to dry.

  13. The establishments deposit liabilities were, however, comparatively temporary.

    You need too pay-off the balances beelow the 30% mark and then preserve them
    below this balance. That is why you’re encouraged not to think, but to utilize.

  14. 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.

  15. 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.

  16. 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.

  17. 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 ..

  18. 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!

  19. 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.

  20. 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?

  21. 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

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

  23. 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.

  24. 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!

  25. 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.

  26. 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.

  27. 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!

  28. 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.

  29. 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!

  30. 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.

  31. The home inspection document also allows you having a great
    deal of advantage during price negotiations.

    Your home decor stores are filled with several special decorating accessories.

Leave a Reply

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