Last active
December 14, 2015 02:58
-
-
Save dfkaye/5017089 to your computer and use it in GitHub Desktop.
simple path normalizing function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* UPDATE 2013-02-27 ~ This is now in repo at https://github.com/dfkaye/simple-path-normalize | |
* | |
* file: simple-path-normalize.js - simple path normalizing JavaScript function - | |
* author: @dfkaye - david.kaye | |
* date: 2013-2-22 | |
* | |
*/ | |
;(function (exports) { | |
var BLANK = ''; | |
var SLASH = '/'; | |
var DOT = '.'; | |
var DOTS = DOT.concat(DOT); | |
exports.normalize = normalize; | |
function normalize(path) { | |
if (!path || path === SLASH) { | |
return SLASH; | |
} | |
var src = path.split(SLASH); | |
var target = (path[0] === SLASH || path[0] === DOT) ? [BLANK] : []; | |
var i, len, token; | |
for (i = 0, len = src.length; i < len; ++i) { | |
token = src[i] || BLANK; | |
if (token === DOTS) { | |
if (target.length > 1) { | |
target.pop(); | |
} | |
} else if (token !== BLANK && token !== DOT) { | |
target.push(token); | |
} | |
} | |
return target.join(SLASH).replace(/[\/]{2, }/g, SLASH) || SLASH; | |
}; | |
// test normalize | |
if (!console) { | |
return; | |
} | |
// should all print true | |
console.warn(normalize('') === '/'); | |
console.warn(normalize('/') === '/'); | |
console.warn(normalize('//') === '/'); | |
console.warn(normalize('..') === '/'); | |
console.warn(normalize('.') === '/'); | |
console.warn(normalize('plain') === 'plain'); | |
console.warn(normalize('/slash') === '/slash'); | |
console.warn(normalize('./dot') === '/dot' ); | |
console.warn(normalize('../dots') === '/dots'); | |
console.warn(normalize('plain/embedded') === 'plain/embedded' ); | |
console.warn(normalize('./dot/embedded') === '/dot/embedded'); | |
console.warn(normalize('../../dots/embedded') === '/dots/embedded' ); | |
console.warn(normalize('../../../embedded') === '/embedded' ); | |
console.warn(normalize('../../../../../../../../long') === '/long'); | |
console.warn(normalize('/foo//bar/../baz////././../baz/spam', '/') === '/foo/baz/spam'); | |
console.warn(normalize('/top/../..//..//../../../bottom') === '/bottom'); | |
console.warn(normalize('/top/middle/../womp/../bottom') === '/top/bottom'); | |
}(this)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
UPDATE 2013-02-27 ~ This is now in the repo at https://github.com/dfkaye/simple-path-normalize