2013-04-13 71 views
1

我想创建一个程序,将数组存储在一个数组中,我所做的是无论程序找到一个分隔符(“”或“,”)它将它推入数组中,我的问题在于它存储即使是分隔符(我必须使用数组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); 

回答

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 = ""; 
    } 
} 
+0

我完美的作品! – mike10101

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); 
+0

'.filter'不是必需的。只要确定你的正则表达式是贪婪的:'[,\ s] +'。 – Blender

+0

是的,它使用拆分方法,但我必须使用我的数组(分隔符= [“”,“,”;;) – mike10101

+0

试试这个:'var r = new RegExp('['+ s.join('')+ ']');' –

0

重新审视这个问题后,我想你需要本地字符串的组合功能和compact method from the excellent underscore library它删除阵列中的'虚假'条目:

$('#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); 
} 
+0

你能否解释一下这是如何将句子分解为单词的? – Blender

+0

您可以使用每个keyUp分析整个字符串。事实上,这可能是一个更好的方法来做到这一点。我会为你重写我的答案。 –