2013-04-13 2 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

난 그냥 정규식 사용합니다 : 당신이 당신의 코드를 수정하는 대신 for 루프의 indexOf를 사용하려면

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

:

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

예 split 메소드와 함께 작동하지만 내 배열을 사용해야합니다 (구분 기호 = [ "", ","];) – 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을 사용하여 전체 문자열을 분석 할 수 있습니다. 실제로이 방법을 사용하는 것이 더 좋은 방법 일 것입니다. 내 대답을 다시 써 줄게. –

관련 문제