2013-04-13 74 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分析整個字符串。事實上,這可能是一個更好的方法來做到這一點。我會爲你重寫我的答案。 –