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.
Comment by Lindsey on 22 January 2016:
Quality articles is the important to attract the visitors to go
to see the web site, that’s what this website is providing.
Comment by Vibhav Agrawal on 1 September 2016:
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
Pingback by URL Parser on 29 October 2016:
[…] Flagrant Badassery – parseUri 1.2: Split URLs in JavaScript […]
Comment by Mezoderma Review on 21 March 2017:
Amazing! Its actually amazing article, I have got much clear idea on the topic of from
this post.
Pingback by Extract hostname name from string - QuestionFocus on 21 December 2017:
[…] because you can have port numbers and special chars. As such, I recommend using something like parseUri to do this for you. I doubt performance is going to be a issue unless you are parsing hundreds of […]
Pingback by Reusable Javascript Functions – Sam East on 22 December 2017:
[…] Url parser taken from this resource. http://blog.stevenlevithan.com/archives/parseuri […]
Comment by Orange Beach Activities on 28 August 2018:
Thanks to my father who stated to me regarding this blog, this blog is genuinely awesome.
Comment by Rudiger on 1 October 2018:
I wish it had the same property names as are available on window.location or in the URL class:
hash, search, href, origin, pathname
Comment by nathan king on 30 October 2018:
thank you.
Comment by download on 24 December 2018:
Wow, that’s what I was seeking for, what a data!
existing here at this weblog, thanks admin of this website.
Pingback by javascript - el uso de javascript para encontrar parámetro en la url y, a continuación, aplicar si entonces la lógica on 21 April 2019:
[…] ParseURI!! blog.stevenlevithan.com/archives/parseuri […]
Pingback by Extract hostname name from string – inneka.com on 1 July 2019:
[…] because you can have port numbers and special chars. As such, I recommend using something like parseUri to do this for you. I doubt performance is going to be a issue unless you are parsing hundreds of […]
Pingback by javascript - utilizzare javascript per trovare parametro nell'url e quindi applicare se poi la logica on 20 December 2019:
[…] ParseURI!! blog.stevenlevithan.com/archives/parseuri […]
Comment by Sean Bannister on 9 May 2020:
I’ve been using this for years but recently found out there’s now a URL parsers in the javascript spec:
https://developer.mozilla.org/en-US/docs/Web/API/URL
Comment by Rudolph Woodcock on 12 June 2020:
Hello there, I’m calling by yourself toward check with if oneself’re hunting for a far better website link indexer. We only comprise remaining the beta check move (GSA discussion board) and the feed-back is Wonderful. As oneself recognize the outdated references within just the business are fewer prosperous for the reason that various Google upgrades. This is not our situation.
Our services is the easiest for Google still on top of that index Bing and Yandex. Our formulation are all infinite, submissions AND variety of URLs, which will make them the least difficult spouse for Website positioning businesses.
We for that reason supply yourself 24 hrs of tests the moment by yourself desire in the direction of verify that we are the great: http://noticias.wtcconfianza.com/LinkClick.aspx?link=http://www.miniurlz.com/LP-IN2
Key: G8D2EZ9P3
Look at oneself before long
Pingback by ???GET??????_javascript?? on 16 September 2020:
[…] 我使用parseUri库。它使您可以完全按照自己的要求进行操作: […]
Pingback by ??????????_javascript?? on 10 October 2020:
[…] 解析URL可能很棘手,因为您可以具有端口号和特殊字符。因此,我建议您使用诸如parseUri之类的方法来执行此操作。我怀疑除非您解析数百个URL,否则性能是否会成为问题。 […]
Pingback by [javascript] ????? ??? ?? ?? ?? - ???? on 18 October 2020:
[…] ??? ??? ? ???? URL ?? ??? ???? ? ????. ??? parseUri ? ?? ?? ?? ??? ?? ? ???? ?? ???? . ?? ?? […]
Pingback by ??????????|jquery?? on 5 November 2020:
[…] 解析URL可能很棘手,因为您可以具有端口号和特殊字符。因此,我建议您使用诸如parseUri之类的方法来执行此操作。我怀疑除非您要解析数百个URL,否则性能是否会成为问题。 […]
Pingback by ????javascript / jquery??????????|jquery?? on 23 December 2020:
[…] 但是,如果您的URI实际上足够复杂,则可以尝试Steven Levithan的parseUri: […]
Comment by Mahesh Technicals on 8 January 2021:
Nice guide thank you.
Mahesh Technicals