2013-05-07 2 views
0

문장에서 총 단어 수를 계산하려고했습니다. Javascript에서 다음 코드를 사용했습니다.자바 스크립트에서 문자열의 총 단어 수를 얻는 방법

function countWords(){ 
    s = document.getElementById("inputString").value; 
    s = s.replace(/(^\s*)|(\s*$)/gi,""); 
    s = s.replace(/[ ]{2,}/gi," "); 
    s = s.replace(/\n /,"\n"); 
    alert(s.split(' ').length); 
} 

그래서 내가 준 경우 다음 입력,

"Hello world" -> alerts 2  //fine 
"Hello world<space>" -> alerts 3 // supposed to alert 2 
"Hello world world" -> alerts 3 //fine 

내가 잘못?

답변

0

이 하나하시기 바랍니다 시도 :

var word = "str"; 
function countWords(word) { 
    var s = word.length; 
    if (s == "") { 
     alert('count is 0') 
    } 
    else { 
     s = s.replace (/\r\n?|\n/g, ' ') 
      .replace (/ {2,}/g, ' ') 
      .replace (/^ /, '') 
      .replace (/ $/, ''); 
     var q = s.split (' '); 
     alert ('total count is: ' + q.length); 
    } 
} 
+1

항상 코드의 형식을 잘못 지정합니까? 그것을 고쳤습니다. – kapa

+0

왜'.length'를''''과 비교하고 있습니까? –

+0

비교하지 않지만 0 단어 인 경우 알림 시간 –

0

문자열의 끝에 구분 기호 (해당 경우 ' ')가 있으면 분할이 분할되어 목록에 마지막으로 [] 항목이 생성됩니다.

1

여기에서 필요한 모든 것을 찾을 수 있습니다.

http://jsfiddle.net/deepumohanp/jZeKu/

var regex = /\s+/gi; 
var wordCount = value.trim().replace(regex, ' ').split(' ').length; 
var totalChars = value.length; 
var charCount = value.trim().length; 
var charCountNoSpace = value.replace(regex, '').length; 

$('#wordCount').html(wordCount); 
$('#totalChars').html(totalChars); 
$('#charCount').html(charCount); 
$('#charCountNoSpace').html(charCountNoSpace); 
0

당신이 할 수있는 것은 (인용 내부 공간 포함) split(" ") 기능을 사용하는 경우에만 구성된 배열로 문자열을 변환하는 것입니다 단어들. 그런 다음 문자열의 단어 수인 array.length을 사용하여 배열의 길이를 가져올 수 있습니다.

관련 문제