【问题标题】:formatting path string in javascript在javascript中格式化路径字符串
【发布时间】:2015-08-23 07:04:43
【问题描述】:

如果您觉得您必须对这个问题投反对票,我将不胜感激:有反馈总比没有反馈好。


我一直在尝试格式化混合路径数组(unix 和 windows 格式)并在某些情况下删除根目录。

但我想知道是否有人可以提出建议:

  • 利用 Nodejs 中的现有函数
  • 或者这样会更有效/更简洁。

源代码:

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])))));
}

想要的输出:

"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

我的目标是自动化 chrome 扩展项目的 installation of bower components with gulp

【问题讨论】:

    标签: javascript node.js path format


    【解决方案1】:
    var output = js.map(function(i){return i + " => " + i.replace(/\\/g, '/').replace(/^dist\//,'');});
    

    【讨论】:

    • 它不适合这个:"dist\vendor\scripts\bootstrap.min.js =&gt; vendor/scripts/bootstrap.min.js"
    • 如果我要安装包example_dist?带路径:dist/example_dist/styles.css
    • 如果是这样,您可以使用.replace(/^dist\//,'');}) 而不是.replace('dist/','')。我相应地进行了更改。
    • 我完全不知道.map 函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-17
    • 1970-01-01
    • 2012-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多