formatting path string in javascript

7.7k views Asked by At

If you feel that you have to down-vote this question I would be grateful that would comment on it: any feedback is better that no feedback.


I have been trying to format an array of mixed path (unix and windows format) and to remove the root directory in certain case.

But I am wondering if someone could suggest something:

  • either that makes use of existing function from Nodejs
  • or that would be more efficient/succint.

source code:

var js = [
  "scripts/content.js",
  "dist/styles/styles.css",
  "dist\\vendor\\scripts\\bootstrap.min.js",
  "dist\\vendor\\scripts\\jquery.min.js"
];

var root = 'dist';

var convertPath = function(path) {
    return path.replace(/\\/g,"/");
};

var splitted = function(path) {
    return path.split('/');
};

var pop = function(arr) {
    var l = arr.length;
    if( arr[0] === root ){
      return arr.splice(1,l-1);
    }
    return arr;
};

var merge = function(arr) {
    return arr.join('/');
};

var length = js.length;
var i = 0;

for(i;i < length; i++){
    console.log(js[i] + ' => ' + merge(pop(splitted(convertPath(js[i])))));
}

desired output:

"scripts/content.js => scripts/content.js"
"dist/styles/styles.css => styles/styles.css"
"dist\vendor\scripts\bootstrap.min.js => vendor/scripts/bootstrap.min.js"
"dist\vendor\scripts\jquery.min.js => vendor/scripts/jquery.min.js"

JSBin preview

My aim is to automate the installation of bower components with gulp for a chrome extension project

1

There are 1 answers

4
Safeer Hussain On BEST ANSWER
var output = js.map(function(i){return i + " => " + i.replace(/\\/g, '/').replace(/^dist\//,'');});