Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Удаляет сегменты с точками из пути.
- *
- * Алгоритм описан по ссылке:
- * https://tools.ietf.org/html/rfc3986#section-5.2.4
- *
- */
- function removeDotSegments(path) {
- var output = [];
- var offset = 0;
- var position;
- var segment;
- // While the input buffer is not empty, loop as follows:
- for (;;) {
- console.log(path.substr(offset));
- // A. If the input buffer begins with a prefix of "../" or "./",
- // then remove that prefix from the input buffer; otherwise,
- if (path.substr(offset, 3) === '../') {
- offset += 2;
- continue;
- }
- if (path.substr(offset, 2) === './') {
- ++offset;
- continue;
- }
- // B. if the input buffer begins with a prefix of "/./" or "/.",
- // where "." is a complete path segment, then replace that
- // prefix with "/" in the input buffer; otherwise,
- if (path.substr(offset, 3) === '/./') {
- offset += 2;
- continue;
- }
- // C. if the input buffer begins with a prefix of "/../" or "/..",
- // where ".." is a complete path segment, then replace that
- // prefix with "/" in the input buffer and remove the last
- // segment and its preceding "/" (if any) from the output
- // buffer; otherwise,
- if (path.substr(offset, 4) === '/../') {
- offset += 3;
- output.pop();
- continue;
- }
- // D. if the input buffer consists only of "." or "..", then remove
- // that from the input buffer; otherwise,
- //
- // E. move the first path segment in the input buffer to the end of
- // the output buffer, including the initial "/" character (if
- // any) and any subsequent characters up to, but not including,
- // the next "/" character or the end of the input buffer.
- position = path.indexOf('/', offset + 1);
- if (position === -1) {
- segment = path.substr(offset);
- if (segment === '/.') {
- // Второе условие A
- output.push('/');
- } else if (segment === '/..') {
- // Второе условие B
- output.pop();
- output.push('/');
- } else if (segment !== '.' && segment !== '..') {
- // D
- output.push(segment);
- }
- break;
- }
- // E
- segment = path.substr(offset, position);
- output.push(segment);
- offset = position;
- }
- return output.join('');
- }
- var paths = [
- '/a/b/c/./../../g',
- 'mid/content=5/../6',
- ];
- paths.forEach((path) => {
- console.log('%s --> %s', path, removeDotSegments(path));
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement