如何删除数组中的空格?

时间:2013-04-13 21:16:36

标签: javascript arrays

我正在尝试创建一个在Array中存储单词的程序,我所做的是无论程序找到一个分隔符(“”或“,”)它将它推送到数组中,我的问题在于它是用它存储分隔符(我必须使用数组SEPARATORS)。

var sentence = prompt("");

var tab = [];

var word = "" ;

var separators = [" ", ","];

for(var i = 0 ; i< sentence.length ; i++){

    for(var j = 0 ; j < separators.length ; j++){

    if(sentence.charAt(i) != separators[j] && j == separators.length-1){

           word += sentence.charAt(i); 

        }else if(sentence.charAt(i) == separators[j]){

           tab.push(word);
           word = "";

        }

    }

}

tab.push(word);
console.log(tab);

3 个答案:

答案 0 :(得分:3)

你可以试试这个:

var text = 'Some test sentence, and a long sentence';
var words = text.split(/,|\s/);

如果您不想要空字符串:

var words = text.split(/,|\s/).filter(function (e) {
    return e.length;
});
console.log(words); //["some", "test", "sentence", "and", "a", "long", "sentence"]

如果您需要使用该阵列,可以试试这个:

var text = 'Some test sentence, and a long sentence',
    s = [',', ' '],
    r = RegExp('[' + s.join('') + ']+'),
    words = text.split(r);

答案 1 :(得分:2)

我只想使用正则表达式:

var words = sentence.split(/[, ]+/);

如果您想修复代码,请使用indexOf代替for循环:

for (var i = 0; i < sentence.length; i++) {
    if (separators.indexOf(sentence.charAt(i)) === -1) {
        word += sentence.charAt(i);
    } else {
        tab.push(word);
        word = "";
    }
}

答案 2 :(得分:0)

重新检查问题后,我认为您需要组合使用本机字符串函数和compact method from the excellent underscore library来删除数组中的'falsy'条目:

$('#textfield).keyup(analyzeString);
var words;
function analyzeString(event){
    words = [];
    var string = $('#textfield).val()
    //replace commas with spaces
    string = string.split(',').join(' ');
    //split the string on spaces 
    words = string.split(' ');
    //remove the empty blocks using underscore compact
    _.compact(words);
}