├── .bowerrc ├── .gitignore ├── .jshintrc ├── .npmignore ├── LICENSE ├── README.md ├── bower.json ├── dist ├── lite-url.js └── lite-url.min.js ├── gulpfile.js ├── karma.conf.js ├── npm-shrinkwrap.json ├── package.json ├── saucelabs.example.json ├── src └── lite-url.js ├── test-browsers.json └── test ├── browser ├── lite-url.test.html └── lite-url.test.js └── node └── lite-url.test.js /.bowerrc: -------------------------------------------------------------------------------- 1 | { 2 | "directory": "libs" 3 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | libs 2 | node_modules 3 | saucelabs.json 4 | .idea/ 5 | *.log -------------------------------------------------------------------------------- /.jshintrc: -------------------------------------------------------------------------------- 1 | { 2 | "node":true, 3 | "bitwise": true, 4 | "curly": true, 5 | "eqeqeq": true, 6 | "forin": true, 7 | "immed": false, 8 | "latedef": false, 9 | "newcap": true, 10 | "noarg": true, 11 | "quotmark": "single", 12 | "undef": true, 13 | "unused": true, 14 | "trailing": true, 15 | "es3":true, 16 | "camelcase": false, 17 | "white": false, 18 | "evil": false, 19 | "browser": true, 20 | "eqnull": true, 21 | "sub": true 22 | } -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | * 2 | !dist/* -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2014-2018 Sam Adams 2 | 3 | Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 4 | 5 | 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 6 | 7 | 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 8 | 9 | 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 10 | 11 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![NPM](https://nodei.co/npm/lite-url.png?downloads=true)](https://nodei.co/npm/lite-url/) 2 | 3 | [![dependencies](https://david-dm.org/sadams/lite-url.png)](https://david-dm.org/sadams/lite-url) 4 | 5 | [![Sauce Test Status](https://saucelabs.com/browser-matrix/samadamslite.svg)](https://saucelabs.com/u/samadamslite) 6 | 7 | # lite-url 8 | 9 | A small cross-browser JS lib for parsing a URL into its component parts. 10 | 11 | Broadly provides the same interface as the native [URL](https://developer.mozilla.org/en-US/docs/Web/API/URL) function, 12 | but in a cross browser way (taken from Chrome 35): 13 | 14 | new URL('http://user:pass@example.com:8080/directory/file.ext?query=1#anchor'); //results in... 15 | 16 | { 17 | "hash": "#anchor", 18 | "search": "?query=1", 19 | "pathname": "/directory/file.ext", 20 | "port": "8080", 21 | "hostname": "example.com", 22 | "host": "example.com:8080", 23 | "password": "pass", 24 | "username": "user", 25 | "protocol": "http:", 26 | "origin": "http://example.com:8080", 27 | "href": "http://user:pass@example.com:8080/directory/file.ext?query=1#anchor" 28 | } 29 | 30 | # install 31 | 32 | ### manual 33 | 34 | grab the minified version from `dist/` 35 | 36 | ### bower 37 | 38 | bower install --save lite-url 39 | 40 | ### npm 41 | 42 | npm install --save lite-url 43 | 44 | (Since node.js already has built-in parsing functionality, 45 | this is only really useful if you are using [browserify](http://browserify.org/) and want to keep the size down). 46 | 47 | 48 | ## 2 variations from chrome 49 | 50 | ### 1. more permissive 51 | 52 | The following will parse in this lib but not in chrome (this is intentional): 53 | 54 | 1. new URL('//user:pass@example.com:8080/directory/file.ext?query=1#anchor'); //results in empty protocol 55 | 1. new URL('?foo=bar&bingobang=&king=kong@kong.com#foobar/bing/bo@ng?b#ang'); //populates only href, hash, search, params 56 | 57 | Both of the above would throw an error in chrome's native URL() parser. 58 | 59 | ### 2. query parser 60 | 61 | Technically, there shouldn't be a parsed version of the query in the result (since the Chrome URL parser doesn't do this). 62 | 63 | If you don't like the behaviour you can change it by calling `changeQueryParser` with a function. 64 | That function will be given the deconstructed url and expects the query params back. 65 | 66 | E.g. If you want duplicate keys to be turned into an array, you could do this: 67 | 68 | liteURL.changeQueryParser(function (uri) { 69 | var params = {}; 70 | 71 | //strip the question mark from search 72 | var query = uri.search ? uri.search.substring(uri.search.indexOf('?') + 1) : ''; 73 | query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function ($0, $1, $2) { 74 | //query isn't actually modified, .replace() is used as an iterator to populate params 75 | if ($1) { 76 | if (params[$1]) { 77 | if (params[$1] instanceof Array) { 78 | params[$1].push($2); 79 | } else { 80 | params[$1] = [params[$1], $2]; 81 | } 82 | } else { 83 | params[$1] = $2; 84 | } 85 | } 86 | }); 87 | return params; 88 | }); 89 | 90 | (The default behaviour will only ever return a string for a key, 91 | and it will be the last string it finds for that key.) 92 | 93 | ## usage 94 | 95 | 96 | 101 | 102 | 103 | ## notes 104 | 105 | The URL object in Chrome etc doesn't quite fit with other interpretations of the spec (http://en.wikipedia.org/wiki/URI_scheme#Examples). 106 | 107 | ## alternatives 108 | 109 | - https://github.com/medialize/URI.js 110 | - good if size isn't an issue 111 | - http://stevenlevithan.com/demo/parseuri/js/ 112 | - good test examples but has a bug or two ('@' symbol in path or query [breaks it](http://stackoverflow.com/questions/24304920/is-the-character-valid-in-a-url-after-the-hostname)) 113 | - `var x = document.createElement('a'); x.href = '/relative/url'; console.log(x.hostname)` 114 | - requires a document and creating an element (just not tidy) 115 | - isn't compatible with lt IE10 116 | - can't get authentication info from URL 117 | - https://developer.mozilla.org/en-US/docs/Web/API/URL 118 | - not cross browser 119 | 120 | ## developing 121 | 122 | ### testing 123 | 124 | npm install -g gulp 125 | npm install && bower install 126 | gulp 127 | 128 | #### crossbrowser testing with saucelabs 129 | 130 | using config file: 131 | 132 | cp saucelabs.example.json saucelabs.json 133 | 134 | add your saucelabs username/secret key, and run: 135 | 136 | npm test 137 | 138 | you can do the same on cmdline with: 139 | 140 | export SAUCE_USERNAME='your username' && export SAUCE_ACCESS_KEY='your key' && npm test 141 | 142 | ### building 143 | 144 | for npm (assuming setup correctly with npm) 145 | 146 | npm publish 147 | 148 | for bower, just tag correct semver and push to github. 149 | -------------------------------------------------------------------------------- /bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "lite-url", 3 | "main": "dist/lite-url.min.js", 4 | "version": "1.0.2", 5 | "authors": [ 6 | "Sam Adams " 7 | ], 8 | "description": "A small cross-browser JS lib for parsing a URL into its component parts (generally follows Chrome's `new URL(parseThisUrl)` API).", 9 | "moduleType": [ 10 | "globals", 11 | "amd", 12 | "node" 13 | ], 14 | "keywords": [ 15 | "url", 16 | "uri", 17 | "url parsing" 18 | ], 19 | "license": "MIT", 20 | "ignore": [ 21 | "**/.*", 22 | "node_modules", 23 | "libs", 24 | "test" 25 | ], 26 | "devDependencies": { 27 | "qunit": "~1.14.0" 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /dist/lite-url.js: -------------------------------------------------------------------------------- 1 | /** 2 | * lite-url - Small, JS lib that uses regex for parsing a URL into it's component parts. 3 | * @version v1.0.5 4 | * @link https://github.com/sadams/lite-url 5 | * @license BSD-3-Clause 6 | */ 7 | (function(){ 8 | 'use strict'; 9 | 10 | /** 11 | * Establish the root object, `window` in the browser, or `exports` on the server. 12 | */ 13 | var root = this; 14 | 15 | /** 16 | * In memory cache for so we don't parse the same url twice 17 | * @type {{}} 18 | */ 19 | var memo = {}; 20 | 21 | /** 22 | * splits a string on the first occurrence of 'splitter' and calls back with the two entries. 23 | * @param {string} str 24 | * @param {string} splitter 25 | * @param {function} callback 26 | * @return * 27 | */ 28 | function splitOnFirst(str, splitter, callback) { 29 | var parts = str.split(splitter); 30 | var first = parts.shift(); 31 | return callback(first, parts.join(splitter)); 32 | } 33 | 34 | /** 35 | * 36 | * @param {string} str - the url to parse 37 | * @returns {{ 38 | * href: string // http://user:pass@host.com:81/directory/file.ext?query=1#anchor 39 | * protocol: string, // http: 40 | * origin: string, // http://user:pass@host.com:81 41 | * host: string, // host.com:81 42 | * hostname: string, // host.com 43 | * port: string, // 81 44 | * pathname: string, // /directory/file.ext 45 | * search: string, // ?query=1 46 | * hash: string, // #anchor 47 | * username: string, // user 48 | * password: string, // pass 49 | * username: string, // user 50 | * }} 51 | */ 52 | function uriParser(str) { 53 | var uri = { 54 | hash:'', 55 | host:'', 56 | hostname:'', 57 | origin:'', 58 | pathname:'', 59 | protocol:'', 60 | search:'', 61 | password:'', 62 | username:'', 63 | port:'' 64 | }; 65 | // http://user:pass@host.com:81/directory/file.ext?query=1#anchor 66 | splitOnFirst(str, '#', function(nonHash, hash) { 67 | // http://user:pass@host.com:81/directory/file.ext?query=1, anchor 68 | if (hash) { 69 | // #anchor 70 | uri.hash = hash ? '#' + hash : ''; 71 | } 72 | // http://user:pass@host.com:81/directory/file.ext?query=1 73 | splitOnFirst(nonHash, '?', function(nonSearch, search) { 74 | // http://user:pass@host.com:81/directory/file.ext, query=1 75 | if (search) { 76 | // ?query=1 77 | uri.search = '?' + search; 78 | } 79 | if (!nonSearch) { 80 | //means we were given a query string only 81 | return; 82 | } 83 | // http://user:pass@host.com:81/directory/file.ext 84 | splitOnFirst(nonSearch, '//', function(protocol, hostUserPortPath) { 85 | // http:, user:pass@host.com:81/directory/file.ext 86 | uri.protocol = protocol; 87 | splitOnFirst(hostUserPortPath, '/', function(hostUserPort, path) { 88 | // user:pass@host.com:81, directory/file.ext 89 | uri.pathname = '/' + (path || ''); // /directory/file.ext 90 | if (uri.protocol || hostUserPort) { 91 | // http://user:pass@host.com:81 92 | uri.origin = uri.protocol + '//' + hostUserPort; 93 | } 94 | // user:pass@host.com:81 95 | splitOnFirst(hostUserPort, '@', function(auth, hostPort){ 96 | // user:pass, host.com:81 97 | if (!hostPort) { 98 | hostPort = auth; 99 | } else { 100 | // user:pass 101 | var userPass = auth.split(':'); 102 | uri.username = userPass[0];// user 103 | uri.password = userPass[1];// pass 104 | } 105 | // host.com:81 106 | uri.host = hostPort; 107 | splitOnFirst(hostPort, ':', function(hostName, port){ 108 | // host.com, 81 109 | uri.hostname = hostName; // host.com 110 | if (port) { 111 | uri.port = port; // 81 112 | } 113 | }); 114 | }); 115 | }); 116 | 117 | }); 118 | }); 119 | }); 120 | 121 | uri.href = uri.origin + uri.pathname + uri.search + uri.hash; 122 | 123 | return uri; 124 | } 125 | 126 | /** 127 | * @param {string} uri 128 | * @returns {{}} 129 | */ 130 | function queryParser(uri) { 131 | var params = {}; 132 | var search = uri.search; 133 | if (search) { 134 | search = search.replace(new RegExp('\\?'), ''); 135 | var pairs = search.split('&'); 136 | for (var i in pairs) { 137 | if (pairs.hasOwnProperty(i) && pairs[i]) { 138 | var pair = pairs[i].split('='); 139 | params[pair[0]] = pair[1]; 140 | } 141 | } 142 | } 143 | return params; 144 | } 145 | 146 | /** 147 | * Uri parsing method. 148 | * 149 | * @param {string} str 150 | * @returns {{ 151 | * href:string, 152 | * origin:string, 153 | * protocol:string, 154 | * username:string, 155 | * password:string, 156 | * host:string, 157 | * hostname:string, 158 | * port:string, 159 | * path:string, 160 | * search:string, 161 | * hash:string, 162 | * params:{} 163 | * }} 164 | */ 165 | function liteURL(str) { 166 | // We first check if we have parsed this URL before, to avoid running the 167 | // monster regex over and over (which is expensive!) 168 | var uri = memo[str]; 169 | 170 | if (typeof uri !== 'undefined') { 171 | return uri; 172 | } 173 | 174 | //parsed url 175 | uri = uriParser(str); 176 | 177 | uri.params = queryParser(uri); 178 | 179 | // Stored parsed values 180 | memo[str] = uri; 181 | 182 | return uri; 183 | } 184 | 185 | liteURL.changeQueryParser = function(parser) { 186 | queryParser = parser; 187 | }; 188 | 189 | //moduleType support 190 | if (typeof exports !== 'undefined') { 191 | //supports node 192 | if (typeof module !== 'undefined' && module.exports) { 193 | exports = module.exports = liteURL; 194 | } 195 | exports.liteURL = liteURL; 196 | } else { 197 | //supports globals 198 | root.liteURL = liteURL; 199 | } 200 | 201 | //supports requirejs/amd 202 | return liteURL; 203 | }).call(this); 204 | -------------------------------------------------------------------------------- /dist/lite-url.min.js: -------------------------------------------------------------------------------- 1 | /** 2 | * lite-url - Small, JS lib that uses regex for parsing a URL into it's component parts. 3 | * @version v1.0.5 4 | * @link https://github.com/sadams/lite-url 5 | * @license BSD-3-Clause 6 | */ 7 | (function(){"use strict";function r(r,n,t){var e=r.split(n),o=e.shift();return t(o,e.join(n))}function n(n){var t={hash:"",host:"",hostname:"",origin:"",pathname:"",protocol:"",search:"",password:"",username:"",port:""};return r(n,"#",function(n,e){e&&(t.hash=e?"#"+e:""),r(n,"?",function(n,e){e&&(t.search="?"+e),n&&r(n,"//",function(n,e){t.protocol=n,r(e,"/",function(n,e){t.pathname="/"+(e||""),(t.protocol||n)&&(t.origin=t.protocol+"//"+n),r(n,"@",function(n,e){if(e){var o=n.split(":");t.username=o[0],t.password=o[1]}else e=n;t.host=e,r(e,":",function(r,n){t.hostname=r,n&&(t.port=n)})})})})})}),t.href=t.origin+t.pathname+t.search+t.hash,t}function t(r){var n={},t=r.search;if(t){t=t.replace(new RegExp("\\?"),"");var e=t.split("&");for(var o in e)if(e.hasOwnProperty(o)&&e[o]){var i=e[o].split("=");n[i[0]]=i[1]}}return n}function e(r){var e=i[r];return"undefined"!=typeof e?e:(e=n(r),e.params=t(e),i[r]=e,e)}var o=this,i={};return e.changeQueryParser=function(r){t=r},"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=e),exports.liteURL=e):o.liteURL=e,e}).call(this); 8 | -------------------------------------------------------------------------------- /gulpfile.js: -------------------------------------------------------------------------------- 1 | var gulp = require('gulp'); 2 | var qunit = require('node-qunit-phantomjs'); 3 | var gulpLoadPlugins = require('gulp-load-plugins'); 4 | var plugins = gulpLoadPlugins(); 5 | 6 | var pkg = require('./package.json'); 7 | var banner = ['/**', 8 | ' * <%= pkg.name %> - <%= pkg.description %>', 9 | ' * @version v<%= pkg.version %>', 10 | ' * @link <%= pkg.homepage %>', 11 | ' * @license <%= pkg.license %>', 12 | ' */', 13 | ''].join('\n'); 14 | 15 | gulp.task('build', function() { 16 | return gulp.src('src/*.js') 17 | .pipe(plugins.header(banner, { pkg : pkg } )) 18 | .pipe(gulp.dest('dist')) 19 | .pipe(plugins.uglify({ 20 | preserveComments: 'some' 21 | })) 22 | .pipe(plugins.rename({ 23 | extname: '.min.js' 24 | })) 25 | .pipe(gulp.dest('dist')) 26 | ; 27 | }); 28 | 29 | gulp.task('qunit', function() { 30 | return qunit('./test/browser/lite-url.test.html'); 31 | }); 32 | 33 | gulp.task('lint', function() { 34 | return gulp.src(['./src/*.js','gulpfile.js','karma.conf.js']) 35 | .pipe(plugins.jshint()) 36 | .pipe(plugins.jshint.reporter('fail')) 37 | ; 38 | }); 39 | 40 | gulp.task('default',['lint','build','qunit']); 41 | -------------------------------------------------------------------------------- /karma.conf.js: -------------------------------------------------------------------------------- 1 | var fs = require('fs'); 2 | 3 | // Use ENV vars on Travis and sauce.json locally to get credentials 4 | if (!process.env.SAUCE_USERNAME) { 5 | if (!fs.existsSync('saucelabs.json')) { 6 | console.log('Missing local sauce.json with SauceLabs credentials.'); 7 | process.exit(1); 8 | } else { 9 | process.env.SAUCE_USERNAME = require('./saucelabs').username; 10 | process.env.SAUCE_ACCESS_KEY = require('./saucelabs').accessKey; 11 | } 12 | } 13 | 14 | module.exports = function(config) { 15 | var customLaunchers = require('./test-browsers.json'); 16 | config.set({ 17 | 18 | // base path, that will be used to resolve files and exclude 19 | basePath: '', 20 | 21 | sauceLabs: { 22 | accessKey: process.env.SAUCE_ACCESS_KEY, 23 | 'idle-timeout': 1000, 24 | recordScreenshots: false, 25 | testName: 'lite-url crossbrowers', 26 | username: process.env.SAUCE_USERNAME 27 | }, 28 | customLaunchers: customLaunchers, 29 | browsers: Object.keys(customLaunchers), 30 | browserDisconnectTimeout: 60 * 1000, 31 | browserDisconnectTolerance: 2, 32 | browserNoActivityTimeout: 60 * 1000, 33 | // If browser does not capture in given timeout [ms], kill it 34 | captureTimeout: 60 * 1000, 35 | reporters: ['dots', 'saucelabs'], 36 | singleRun: true, 37 | 38 | // frameworks to use 39 | frameworks: ['qunit'], 40 | 41 | // list of files / patterns to load in the browser 42 | //passed in from gulp 43 | files:[ 44 | './dist/lite-url.min.js', 45 | './test/browser/*.test.js' 46 | ], 47 | 48 | // Log output from the `sc` process to stdout? 49 | verbose: true, 50 | 51 | // Enable verbose debugging (optional) 52 | verboseDebugging: true, 53 | 54 | // web server port 55 | port: 9876, 56 | 57 | // enable / disable colors in the output (reporters and logs) 58 | colors: true, 59 | 60 | // level of logging 61 | // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG 62 | logLevel: config.LOG_INFO 63 | }); 64 | }; -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "lite-url", 3 | "version": "1.0.5", 4 | "authors": [ 5 | "Sam Adams " 6 | ], 7 | "description": "A small cross-browser JS lib for parsing a URL into its component parts (generally follows Chrome's `new URL(parseThisUrl)` API).", 8 | "keywords": [ 9 | "url", 10 | "uri", 11 | "url parsing" 12 | ], 13 | "license": "BSD-3-Clause", 14 | "homepage": "https://github.com/sadams/lite-url", 15 | "bugs": "https://github.com/sadams/lite-url/issues", 16 | "repository": { 17 | "type": "git", 18 | "url": "https://github.com/sadams/lite-url.git" 19 | }, 20 | "main": "dist/lite-url.min.js", 21 | "scripts": { 22 | "test": "karma start --single-run" 23 | }, 24 | "devDependencies": { 25 | "gulp": "^3.8.10", 26 | "gulp-header": "^1.2.2", 27 | "gulp-jshint": "^1.9.0", 28 | "gulp-karma": "0.0.4", 29 | "gulp-load-plugins": "^0.8.0", 30 | "gulp-rename": "^1.2.0", 31 | "gulp-uglify": "^1.1.0", 32 | "karma": "^0.12.31", 33 | "karma-cli": "0.0.4", 34 | "karma-qunit": "^0.1.4", 35 | "karma-sauce-launcher": "^0.2.10", 36 | "node-qunit-phantomjs": "^1.2.0" 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /saucelabs.example.json: -------------------------------------------------------------------------------- 1 | { 2 | "username":"youusername", 3 | "accessKey":"youraccesskey" 4 | } -------------------------------------------------------------------------------- /src/lite-url.js: -------------------------------------------------------------------------------- 1 | (function(){ 2 | 'use strict'; 3 | 4 | /** 5 | * Establish the root object, `window` in the browser, or `exports` on the server. 6 | */ 7 | var root = this; 8 | 9 | /** 10 | * In memory cache for so we don't parse the same url twice 11 | * @type {{}} 12 | */ 13 | var memo = {}; 14 | 15 | /** 16 | * splits a string on the first occurrence of 'splitter' and calls back with the two entries. 17 | * @param {string} str 18 | * @param {string} splitter 19 | * @param {function} callback 20 | * @return * 21 | */ 22 | function splitOnFirst(str, splitter, callback) { 23 | var parts = str.split(splitter); 24 | var first = parts.shift(); 25 | return callback(first, parts.join(splitter)); 26 | } 27 | 28 | /** 29 | * 30 | * @param {string} str - the url to parse 31 | * @returns {{ 32 | * href: string // http://user:pass@host.com:81/directory/file.ext?query=1#anchor 33 | * protocol: string, // http: 34 | * origin: string, // http://user:pass@host.com:81 35 | * host: string, // host.com:81 36 | * hostname: string, // host.com 37 | * port: string, // 81 38 | * pathname: string, // /directory/file.ext 39 | * search: string, // ?query=1 40 | * hash: string, // #anchor 41 | * username: string, // user 42 | * password: string, // pass 43 | * username: string, // user 44 | * }} 45 | */ 46 | function uriParser(str) { 47 | var uri = { 48 | hash:'', 49 | host:'', 50 | hostname:'', 51 | origin:'', 52 | pathname:'', 53 | protocol:'', 54 | search:'', 55 | password:'', 56 | username:'', 57 | port:'' 58 | }; 59 | // http://user:pass@host.com:81/directory/file.ext?query=1#anchor 60 | splitOnFirst(str, '#', function(nonHash, hash) { 61 | // http://user:pass@host.com:81/directory/file.ext?query=1, anchor 62 | if (hash) { 63 | // #anchor 64 | uri.hash = hash ? '#' + hash : ''; 65 | } 66 | // http://user:pass@host.com:81/directory/file.ext?query=1 67 | splitOnFirst(nonHash, '?', function(nonSearch, search) { 68 | // http://user:pass@host.com:81/directory/file.ext, query=1 69 | if (search) { 70 | // ?query=1 71 | uri.search = '?' + search; 72 | } 73 | if (!nonSearch) { 74 | //means we were given a query string only 75 | return; 76 | } 77 | // http://user:pass@host.com:81/directory/file.ext 78 | splitOnFirst(nonSearch, '//', function(protocol, hostUserPortPath) { 79 | // http:, user:pass@host.com:81/directory/file.ext 80 | uri.protocol = protocol; 81 | splitOnFirst(hostUserPortPath, '/', function(hostUserPort, path) { 82 | // user:pass@host.com:81, directory/file.ext 83 | uri.pathname = '/' + (path || ''); // /directory/file.ext 84 | if (uri.protocol || hostUserPort) { 85 | // http://user:pass@host.com:81 86 | uri.origin = uri.protocol + '//' + hostUserPort; 87 | } 88 | // user:pass@host.com:81 89 | splitOnFirst(hostUserPort, '@', function(auth, hostPort){ 90 | // user:pass, host.com:81 91 | if (!hostPort) { 92 | hostPort = auth; 93 | } else { 94 | // user:pass 95 | var userPass = auth.split(':'); 96 | uri.username = userPass[0];// user 97 | uri.password = userPass[1];// pass 98 | } 99 | // host.com:81 100 | uri.host = hostPort; 101 | splitOnFirst(hostPort, ':', function(hostName, port){ 102 | // host.com, 81 103 | uri.hostname = hostName; // host.com 104 | if (port) { 105 | uri.port = port; // 81 106 | } 107 | }); 108 | }); 109 | }); 110 | 111 | }); 112 | }); 113 | }); 114 | 115 | uri.href = uri.origin + uri.pathname + uri.search + uri.hash; 116 | 117 | return uri; 118 | } 119 | 120 | /** 121 | * @param {string} uri 122 | * @returns {{}} 123 | */ 124 | function queryParser(uri) { 125 | var params = {}; 126 | var search = uri.search; 127 | if (search) { 128 | search = search.replace(new RegExp('\\?'), ''); 129 | var pairs = search.split('&'); 130 | for (var i in pairs) { 131 | if (pairs.hasOwnProperty(i) && pairs[i]) { 132 | var pair = pairs[i].split('='); 133 | params[pair[0]] = pair[1]; 134 | } 135 | } 136 | } 137 | return params; 138 | } 139 | 140 | /** 141 | * Uri parsing method. 142 | * 143 | * @param {string} str 144 | * @returns {{ 145 | * href:string, 146 | * origin:string, 147 | * protocol:string, 148 | * username:string, 149 | * password:string, 150 | * host:string, 151 | * hostname:string, 152 | * port:string, 153 | * path:string, 154 | * search:string, 155 | * hash:string, 156 | * params:{} 157 | * }} 158 | */ 159 | function liteURL(str) { 160 | // We first check if we have parsed this URL before, to avoid running the 161 | // monster regex over and over (which is expensive!) 162 | var uri = memo[str]; 163 | 164 | if (typeof uri !== 'undefined') { 165 | return uri; 166 | } 167 | 168 | //parsed url 169 | uri = uriParser(str); 170 | 171 | uri.params = queryParser(uri); 172 | 173 | // Stored parsed values 174 | memo[str] = uri; 175 | 176 | return uri; 177 | } 178 | 179 | liteURL.changeQueryParser = function(parser) { 180 | queryParser = parser; 181 | }; 182 | 183 | //moduleType support 184 | if (typeof exports !== 'undefined') { 185 | //supports node 186 | if (typeof module !== 'undefined' && module.exports) { 187 | exports = module.exports = liteURL; 188 | } 189 | exports.liteURL = liteURL; 190 | } else { 191 | //supports globals 192 | root.liteURL = liteURL; 193 | } 194 | 195 | //supports requirejs/amd 196 | return liteURL; 197 | }).call(this); -------------------------------------------------------------------------------- /test-browsers.json: -------------------------------------------------------------------------------- 1 | { 2 | "sl_chrome_linux": { 3 | "base": "SauceLabs", 4 | "browserName": "chrome", 5 | "platform": "linux" 6 | } 7 | } -------------------------------------------------------------------------------- /test/browser/lite-url.test.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 |
18 | 19 | -------------------------------------------------------------------------------- /test/browser/lite-url.test.js: -------------------------------------------------------------------------------- 1 | (function(){ 2 | var tests = [ 3 | { 4 | "arguments":['http://www.example.com'], 5 | "expected":{ 6 | "hash": "", 7 | "search": "", 8 | "pathname": "/", 9 | "port": "", 10 | "hostname": "www.example.com", 11 | "host": "www.example.com", 12 | "password": "", 13 | "username": "", 14 | "protocol": "http:", 15 | "origin": "http://www.example.com", 16 | "href": "http://www.example.com/", 17 | "params": {} 18 | } 19 | }, 20 | { 21 | "arguments":['http://www.example.com/#asdf'], 22 | "expected":{ 23 | "hash": "#asdf", 24 | "search": "", 25 | "pathname": "/", 26 | "port": "", 27 | "hostname": "www.example.com", 28 | "host": "www.example.com", 29 | "password": "", 30 | "username": "", 31 | "protocol": "http:", 32 | "origin": "http://www.example.com", 33 | "href": "http://www.example.com/#asdf", 34 | "params": {} 35 | } 36 | }, 37 | { 38 | "arguments":['http://www.example.com?foo=bar'], 39 | "expected":{ 40 | "hash": "", 41 | "search": "?foo=bar", 42 | "pathname": "/", 43 | "port": "", 44 | "hostname": "www.example.com", 45 | "host": "www.example.com", 46 | "password": "", 47 | "username": "", 48 | "protocol": "http:", 49 | "origin": "http://www.example.com", 50 | "href": "http://www.example.com/?foo=bar", 51 | "params": { 52 | "foo": "bar" 53 | } 54 | } 55 | }, 56 | { 57 | "arguments":['https://www.example.com/my/path'], 58 | "expected":{ 59 | "hash": "", 60 | "search": "", 61 | "pathname": "/my/path", 62 | "port": "", 63 | "hostname": "www.example.com", 64 | "host": "www.example.com", 65 | "password": "", 66 | "username": "", 67 | "protocol": "https:", 68 | "origin": "https://www.example.com", 69 | "href": "https://www.example.com/my/path", 70 | "params": {} 71 | } 72 | }, 73 | { 74 | "arguments":['http://www.example.com?foo=bar&bingobang=&king=kong@kong.com#foobar/bing/bo@ng?bang'], 75 | "expected":{ 76 | "hash": "#foobar/bing/bo@ng?bang", 77 | "search": "?foo=bar&bingobang=&king=kong@kong.com", 78 | "pathname": "/", 79 | "port": "", 80 | "hostname": "www.example.com", 81 | "host": "www.example.com", 82 | "password": "", 83 | "username": "", 84 | "protocol": "http:", 85 | "origin": "http://www.example.com", 86 | "href": "http://www.example.com/?foo=bar&bingobang=&king=kong@kong.com#foobar/bing/bo@ng?bang", 87 | "params": { 88 | "foo": "bar", 89 | "bingobang": "", 90 | "king": "kong@kong.com" 91 | } 92 | } 93 | }, 94 | { 95 | "arguments":['http://a:b@example.com:890/path/wah@t/foo.js?foo=bar&bingobang=&king=kong@kong.com#foobar/bing/bo@ng?bang'], 96 | "expected":{ 97 | "hash": "#foobar/bing/bo@ng?bang", 98 | "search": "?foo=bar&bingobang=&king=kong@kong.com", 99 | "pathname": "/path/wah@t/foo.js", 100 | "port": "890", 101 | "hostname": "example.com", 102 | "host": "example.com:890", 103 | "password": "b", 104 | "username": "a", 105 | "protocol": "http:", 106 | "origin": "http://a:b@example.com:890", 107 | "href": "http://a:b@example.com:890/path/wah@t/foo.js?foo=bar&bingobang=&king=kong@kong.com#foobar/bing/bo@ng?bang", 108 | "params": { 109 | "foo": "bar", 110 | "bingobang": "", 111 | "king": "kong@kong.com" 112 | } 113 | } 114 | }, 115 | { 116 | "arguments":['//a:b@example.com:890/path/wah@t/foo.js?foo=bar&bingobang=&king=kong@kong.com#foobar/bing/bo@ng?bang'], 117 | "expected":{ 118 | "hash": "#foobar/bing/bo@ng?bang", 119 | "search": "?foo=bar&bingobang=&king=kong@kong.com", 120 | "pathname": "/path/wah@t/foo.js", 121 | "port": "890", 122 | "hostname": "example.com", 123 | "host": "example.com:890", 124 | "password": "b", 125 | "username": "a", 126 | "protocol": "", 127 | "origin": "//a:b@example.com:890", 128 | "href": "//a:b@example.com:890/path/wah@t/foo.js?foo=bar&bingobang=&king=kong@kong.com#foobar/bing/bo@ng?bang", 129 | "params": { 130 | "foo": "bar", 131 | "bingobang": "", 132 | "king": "kong@kong.com" 133 | } 134 | } 135 | }, 136 | { 137 | "arguments": ['?foo=bar&bingobang=&king=kong@kong.com#foobar/bing/bo@ng?b#ang'], 138 | "expected": { 139 | "hash": "#foobar/bing/bo@ng?b#ang", 140 | "search": "?foo=bar&bingobang=&king=kong@kong.com", 141 | "pathname": "", 142 | "port": "", 143 | "hostname": "", 144 | "host": "", 145 | "password": "", 146 | "username": "", 147 | "protocol": "", 148 | "origin": "", 149 | "href": "?foo=bar&bingobang=&king=kong@kong.com#foobar/bing/bo@ng?b#ang", 150 | "params": { 151 | "foo": "bar", 152 | "bingobang": "", 153 | "king": "kong@kong.com" 154 | } 155 | } 156 | }, 157 | { 158 | "arguments":['http://192.20.10.112?foo=bar&bingobang=&king=kong@kong.com#foobar/bing/bo@ng?bang'], 159 | "expected":{ 160 | "hash": "#foobar/bing/bo@ng?bang", 161 | "search": "?foo=bar&bingobang=&king=kong@kong.com", 162 | "pathname": "/", 163 | "port": "", 164 | "hostname": "192.20.10.112", 165 | "host": "192.20.10.112", 166 | "password": "", 167 | "username": "", 168 | "protocol": "http:", 169 | "origin": "http://192.20.10.112", 170 | "href": "http://192.20.10.112/?foo=bar&bingobang=&king=kong@kong.com#foobar/bing/bo@ng?bang", 171 | "params": { 172 | "foo": "bar", 173 | "bingobang": "", 174 | "king": "kong@kong.com" 175 | } 176 | } 177 | }, 178 | { 179 | "arguments":['http://192.20.10.112?&bingobang=&king=kong@kong.com#foobar/bing/bo@ng?bang'], 180 | "expected":{ 181 | "hash": "#foobar/bing/bo@ng?bang", 182 | "search": "?&bingobang=&king=kong@kong.com", 183 | "pathname": "/", 184 | "port": "", 185 | "hostname": "192.20.10.112", 186 | "host": "192.20.10.112", 187 | "password": "", 188 | "username": "", 189 | "protocol": "http:", 190 | "origin": "http://192.20.10.112", 191 | "href": "http://192.20.10.112/?&bingobang=&king=kong@kong.com#foobar/bing/bo@ng?bang", 192 | "params": { 193 | "bingobang": "", 194 | "king": "kong@kong.com" 195 | } 196 | } 197 | } 198 | ]; 199 | for (var i in tests) { 200 | if (tests.hasOwnProperty(i)) { 201 | var test = tests[i]; 202 | (function(test){ 203 | QUnit.test("test url: " + test.arguments[0], function(assert){ 204 | var actual = liteURL.apply(this, test.arguments); 205 | assert.deepEqual(actual, test.expected, "liteURL didn't like: " + test.arguments.join(', ')); 206 | }); 207 | })(test); 208 | } 209 | } 210 | })(); 211 | QUnit.test("query parser", function(assert){ 212 | liteURL.changeQueryParser(function (uri) { 213 | var params = {}; 214 | 215 | //strip the question mark from search 216 | var query = uri.search ? uri.search.substring(uri.search.indexOf('?') + 1) : ''; 217 | query.replace(/(?:^|&)([^&=]*)=?([^&]*)/g, function ($0, $1, $2) { 218 | //query isn't actually modified, .replace() is used as an iterator to populate params 219 | if ($1) { 220 | if (params[$1]) { 221 | if (params[$1] instanceof Array) { 222 | params[$1].push($2); 223 | } else { 224 | params[$1] = [params[$1], $2]; 225 | } 226 | } else { 227 | params[$1] = $2; 228 | } 229 | } 230 | }); 231 | return params; 232 | }); 233 | 234 | var url = 'http://www.example.com?foo=bar&foo=pub&lipsum=lorem&lipsum=ipsum&lipsum=dolor#foobar/bing/bo@ng?bang'; 235 | var expected = { 236 | "hash": "#foobar/bing/bo@ng?bang", 237 | "search": "?foo=bar&foo=pub&lipsum=lorem&lipsum=ipsum&lipsum=dolor", 238 | "pathname": "/", 239 | "port": "", 240 | "hostname": "www.example.com", 241 | "host": "www.example.com", 242 | "password": "", 243 | "username": "", 244 | "protocol": "http:", 245 | "origin": "http://www.example.com", 246 | "href": "http://www.example.com/?foo=bar&foo=pub&lipsum=lorem&lipsum=ipsum&lipsum=dolor#foobar/bing/bo@ng?bang", 247 | "params": { 248 | "foo": [ 249 | "bar", 250 | "pub" 251 | ], 252 | "lipsum": [ 253 | "lorem", 254 | "ipsum", 255 | "dolor" 256 | ] 257 | } 258 | }; 259 | var actual = liteURL(url); 260 | assert.deepEqual(actual, expected, "liteURL didn't use new parser for query params in: " + url); 261 | }); -------------------------------------------------------------------------------- /test/node/lite-url.test.js: -------------------------------------------------------------------------------- 1 | var liteUrl = require('../../'); 2 | exports.basicTest = function(test){ 3 | //more advanced tests are run through browser 4 | var url = 'http://a:b@example.com:890/path/wah@t/foo.js?foo=bar&bingobang=&king=kong@kong.com#foobar/bing/bo@ng?bang'; 5 | var expected = { 6 | "hash": "#foobar/bing/bo@ng?bang", 7 | "search": "?foo=bar&bingobang=&king=kong@kong.com", 8 | "pathname": "/path/wah@t/foo.js", 9 | "port": "890", 10 | "hostname": "example.com", 11 | "host": "example.com:890", 12 | "password": "b", 13 | "username": "a", 14 | "protocol": "http:", 15 | "origin": "http://a:b@example.com:890", 16 | "href": "http://a:b@example.com:890/path/wah@t/foo.js?foo=bar&bingobang=&king=kong@kong.com#foobar/bing/bo@ng?bang", 17 | "params": { 18 | "foo": "bar", 19 | "bingobang": "", 20 | "king": "kong@kong.com" 21 | } 22 | }; 23 | test.deepEqual(liteUrl(url), expected, "url didn't match expected parsed output"); 24 | test.done(); 25 | }; --------------------------------------------------------------------------------