JSFiddle - React, Tailwind, and code Playground

by ti2005

JavaScript

/*
Given a string which is Unix-style path, simplify to canonical path.

  Input: path = "/home/.."
  Output: "/home"

  Input: path = "/../"
  Output: "/"

  Input: path = "/home//foo/"
  Output: "/home/foo"

  Input: path = "/a/./b/../../c/"
  Output: "/c"

*/


function getCanonicalPath(path) {
  if (!path)
    return '/';
  var path = path.split('/');
  let output = [];
  for (let i = 0; i < path.length; i++) {
    if (path[i] && path[i] != '.') {
      if (path[i] === '..' && output.length > 0) {
        output.pop();
      } else {
        if (path[i] != '..' && output.length != 0) {
          output.push(path[i]);
        }
      }
    }
  }
  return '/' + output.join('/').toString();
}

var result = getCanonicalPath("/../");
console.log(result);