Flagrant Badassery

A JavaScript and regular expression centric blog

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.

Try the demo, but make sure to come back and read the details below.

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 or run the test suite.

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.

There Are 229 Responses So Far. »

  1. Link exchange is nothing else however it is only placing the
    other person’s website link on your page at proper place and
    other person will also do similar in favor of you.

  2. I read this post fully about the resemblance of most recent and preceding
    technologies, it’s awesome article.

  3. Good day! This post could not be written any
    better! Reading through this post reminds me of my previous room mate!

    He always kept chatting about this. I will forward this article to him.
    Pretty sure he will have a good read. Many thanks for sharing!

  4. Hello!
    Can everyone hold the exact same complications when i complete?
    I cannot apparently anymore meet my own associate from the master bedroom.
    Soon after possessing several young children We’ve shed the actual
    baby-belly extra fat however I am unable to apparently re-tighten my personal vagina.
    I can regularly accomplish other items to generate your ex content inside the bed room mainly because penile
    making love no longer excites him. Help! We’ve began considering items and
    also approaches to resolve this specific, can easily any
    person propose a fantastic just one?
    Appreciate it!

  5. […] my birth […]

  6. Hello great blog! Does running a blog likoe this
    take a lot of work? I have absolutely no expertise in computer
    programming but I was hoping to start my own blog in the near future.

    Anyway, should youu have any recommendations or techniques
    foor new blog owners please share. I kow this is off subject however I simply haad to ask.
    Kudos!

  7. After looking over a number of the articles on your site, I
    really appreciate your technique of blogging. I added it to my bookmark website list and will be checking back soon. Take a look at my website as well
    and tell me how you feel.

  8. In adding ? , it appear to work

    ^(?:(?![^:@?]+:[^:@?\/]*@?)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@?]*)(?::([^:@?]*))?)?@?)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)

  9. This page certainly has all the information I wanted concerning
    this subject and didn’t know who to ask.

  10. Established in 1993, MAi – SPACE has approximately 250 employees worldwide, and
    a North American installed base of more than $150 million. Why have you been the lucky one chosen by the Invader.
    You may be able to have a scented candle in your space.

  11. Hmm is anyone else encountering problems with the images on this blog loading?
    I’m trying to determine if its a problem on my end or if
    it’s the blog. Any responses would be greatly appreciated.

  12. An attempt at a pimple pop too early is not going to result in anything however ache and will end
    in one thing that anybody with a huge zit needs to happen.
    In actual fact, making an attempt to hurry a pimple will most certainly end in that unhealthy boy sticking around
    for many days longer.

  13. Un post rem?l? d? ?onseils

  14. The demo link does not work anymore. Anyone has it work on your sites?

  15. Anyone has it work on your sites? Is there a updated version?

  16. I always spent my half an hour to read this webpage’s articles
    or reviews all the time along with a mug of coffee.

  17. The last 2 steps to getting them Ultimate are the identical.

  18. Why can’t we know disable javascript in firefox whereas we can do the same in google chrome.

  19. Then you are able to just fill the on the internet form which usually saves your time and energy ,
    as you don’t have for one to visit the business
    in individual. The best way out for that is to get
    in touch with the Bankruptcy lawyer Arlington TX. Lying, when done for skiptracing purposes is called pretexting.

  20. When some one searches for his required thing, therefore he/she wishes to be available
    that in detail, so that thing is maintained over here.

  21. Thank for share.

  22. It’s awesome in favor of me to have a web page, which is helpful in favor of
    my knowledge. thanks admin

  23. I’d like to find out more? I’d care to find
    out more details.

  24. Clicking on the link in the article above, labelled “Try the demo” results in the following error;
    Error occurred: 403 – forbidden
    Apache Server at: s1075064.instanturl.net

  25. […] have a nice API for parsing a URI. It’s based on work by Steven Levithan from way back in 2007.  I wanted to bring it up to date and re-write it as a class in ECMAScript 2015.  I […]

  26. Quality articles is the important to attract the visitors to go
    to see the web site, that’s what this website is providing.

  27. This post gives clear idea in support of the new viewers of blogging, that genuinely how to do blogging.

  28. Hello there, You have done an incredible job. I’ll certainly digg it and
    personally suggest to my friends. I am confident they’ll be benefited from this site.

  29. Hello Steven,
    We were using this script and it really works well.
    However, recently, we ran into an issue, if we use IPv6 URL [like http://%5B2001:ae::52]/index.html?query=value ]
    The script ends up with incorrect parameter values for file, host, path etc.

    So, I was wondering if there is a newer version which handles IPv6 URIs as well?

    Thanks in advance.

    Thanks,
    Vibhav

Post a Response

If you are about to post code, please escape your HTML entities (&amp;, &gt;, &lt;).