Skip to content

Instantly share code, notes, and snippets.

@dfkaye
Last active December 14, 2015 02:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dfkaye/5017089 to your computer and use it in GitHub Desktop.
Save dfkaye/5017089 to your computer and use it in GitHub Desktop.
simple path normalizing function
/**
* 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));
@dfkaye
Copy link
Author

dfkaye commented Feb 27, 2013

UPDATE 2013-02-27 ~ This is now in the repo at https://github.com/dfkaye/simple-path-normalize

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment