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 246 Responses So Far. »

  1. Your means of telling everything in thjis post is actually
    nice, all be able to simply know it, Thanks a lot.

  2. It is perfect time to make some plans for the future
    and it’s time to be happy. I have read this publish and if I may just I desire
    to suggest you some fascinating issues or advice.
    Maybe you can write next articles regarding this article.
    I want to read more issues about it!

  3. Thanks in favor of sharing such a nice opinion, post is nice, thats
    why i have read it fully

  4. Hi there, this weekend is nice for me, as this time i am reading this great educational post here at my house.

  5. Thank you for sharing your info. I really appreciate your efforts and I will
    be waiting for your further post thank you once again.

  6. Hmm it appears like your website ate my first comment
    (it was super long) so I guess I’ll just sum it up what I
    wrote and say, I’m thoroughly enjoying your blog. I too am an aspiring blog blogger but I’m still new to the whole thing.
    Do you have any points for rookie blog writers?
    I’d really appreciate it.

  7. Experienced staff: unlicensed contractors Construction of restaurants.
    Take a look at a fair estimate including unlicensed contractors a lawn-mowing contract that lists all the operations.
    They pleaded guilty to charges related to a
    summary report. Listing $30, 000. One thing you should at least
    twice in a contractor be? They tell you almost certainly
    know you’re in need of their necessary activities
    like others.

  8. Valuable info. Fortunate me I discovered your website by chance, and I am shocked why
    this coincidence did not happened in advance! I bookmarked it.

  9. I do not even know how I ended up here, but I thought this post was good.

    I don’t know who you are but definitely you are going to a famous blogger
    if you are not already 😉 Cheers!

  10. If some one needs to be updated with most recent technologies after that
    he must be go to see this site and be up to date daily.

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

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

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

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

  15. […] my birth […]

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

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

  18. In adding ? , it appear to work

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

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

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

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

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

  23. You actually make it appear so easy together with your
    presentation however I find this topic to be really something which
    I feel I might by no means understand. It seems too complicated and
    extremely vast for me. I am taking a look forward to your next post, I will try
    to get the hold of it!

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

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

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

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

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

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

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

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

  32. Thank for share.

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

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

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

  36. […] 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 […]

  37. 8, while carrying out a discovery concerning a separate violation” including Taylor, cops found the
    photos on Taylor’s mobile phone, the affidavit states.

  38. Thank you for every other magnificent article.

    The place else could anyone get that kind of information in such an ideal means of writing?
    I have a presentation subsequent week, and I am on the search for such information.

  39. The bags are made from different materials that range from leather
    to suede. Grace Kelly even sported a custom
    “Flora” foulard designed especially for her by
    Rodolfo Gucci. These bag factories employ some individuals who concentrate on a particular part of handbag creating.

  40. http://toyota-saigon.vn/

  41. For a small company, they could rely on personnels
    outsourcing companies for jobs like fringe benefit services and also management, pay-roll, recruitment and so on

  42. Home loan Solutions Inspector – Marin & West CCC, CA Commercial property Examiner – Philly, PA Self motivated people needed to check
    for property damages.

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

  44. Your site could be primary today, but as your competition avails of better seo solutions, you could be dislodged tomorrow, so you will constantly have to search for
    even far better search engine optimization solutions to gain back the leading location.

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

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

Post a Response

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