从数组中删除注释和空格而不会丢失0

时间:2016-06-19 01:49:53

标签: javascript arrays

我如何使用此

//arr.filter(function(e){ 
  return e === 0 || e 
}); 

在我的功能?

function stringToArray(splitString) {
    return splitString.split("\n");
}

我创建了一个数组,将我的字符串拆分为新数组,但我想删除空格和注释进入数组。我也想保留0,因为我希望程序正在努力在完成时给我二进制文件。

2 个答案:

答案 0 :(得分:1)

假设您要分别测试每一行(因此没有/**/的多行注释),那么.filter()很容易排出空字符串或那些从//开始:

function stringToArray(splitString) {
    return splitString.split("\n").filter(function(v) {
        return v != "" && v.indexOf("//") != 0;
    });
}

或者如果你想忽略那些非空但只包含空格的行,或者在开头有空格后跟注释的行,你可以使用正则表达式测试,可能是这样的:

function stringToArray(splitString) {
    return splitString.split("\n").filter(function(v) {
         return !/^\s*(\/\/.*)?$/.test(v);
    });
}

答案 1 :(得分:1)

您的问题可能是以下答案;

var code = 'some code here; // an a comment\n more code; //comment\n\n\n\n\ some code here; \nafter some empty lines more code; // and comment\n //comment line\n\n\n             tons of space and more code;\n0  code with zero //this line starts with a zero //',
   codar = code.split(/\n+/).map(s => s.replace(/\s+/g,"").replace(/\/\/.+/g,"")).filter(s => s === 0||s);
console.log(codar);