2012-05-18 3 views
0

이 코드는 html 편집기에서 단어 수를 세는 데 사용됩니다.단어 계산을위한 javascript 정규식

(providing htmlData has already been set) 
var rawWords = htmlData.replace(/<(?:.|\s)*?>/g, '') 
         .replace(/(\r\n|\n|\r)/gm,' '); 
var filteredWords = rawWords.replace(/\[([^\]]+)\]/g,'') 
          .replace(/\s+/g, " ") 
          .replace(/^\s+|\s+$/g, ""); 

내가 이해 한대로, 첫 번째 줄은 html을 제거한 다음 반환을 제거합니다.

다음 줄은 괄호 안에 아무것도 (이 단어 수를 영향을주지 않고 메모를 추가하는 것입니다)를 제거하고 여분의 공백

을 제거하지만이 입력하는 경우 :

Apple 


Charlie 

Tom 

를 그것은 나에게 단어를 제공합니다 3이 아니라 6이됩니다. 왜 그런가? 나는 정규 표현식이 좋지 않다 !!

고마워요

+0

실제로 단어를 계산하는 함수는 어디에 있습니까? – joe92

+0

아마도 단어 카운터가 공백에서 분할을 수행하고 있습니다. 즉 6 라인 = 6 워드이다. – ansiart

답변

1

이 시도, 그냥 공백/숫자를 분할, 간단하고, 배열을 계산합니다. 아래

window.onload = function() { 

    // get string as text 
    var text = document.body.innerText; 

    // replace all non letters (so we don't count 1 as a word) 
    text  = text.replace(/[^a-zA-Z\s]/g, ''); 

    // split on whitespace 
    var words = text.split(/[\s]+/); 

    // output -- 52 
    console.log('numwords', words, words.length); // numwords 52 
} 

전체 예제 :

<html> 
<head> 
<script type="text/javascript">// script</script> 
</head> 
<body> 

a b c d e f g 
1 1 1 1 1 1 1 




the quick brown fox jumped over the lazy dog. 
the quick brown fox jumped over the lazy dog. 
the quick brown fox jumped over the lazy dog.<br><br><br><br><br> 
the quick brown fox jumped over the lazy dog. 
the quick brown fox jumped over the lazy dog. 

</body> 
</html> 
1

이 정규 표현식은 추악하고 중복됩니다. 간단한 정규식이를 통해 다음

var a=document.createElement('div') 
a.innerHTML=htmlData; 
textData=a.innerText 

루프 카운터 증가 : 내 조언은 같은 것을 수행하여 청소 HTML을 얻을 것

var patt=new RegExp(/(^|\W)(\w+)($|\W)/g); 
var counter=0; 
var result=patt.exec(textData); 
while(result!=null) { 
    counter++; 
    result=patt.exec(textData); 
} 

이 매우 조잡를 (그리고 많이한다 당신을 위해 작동하지 않을 수도있는 가정들) 그러나, 당신은 "단어"[당신이해야 할 일의 정의]의 수를 카운터에 넣을 것이고, B/당신은 당신이 원하는 바를 얻기 전에 엄청난 양의 텍스트를 제거하십시오.

HTH

0

가 "로 공간을 교체"이런 식으로 worj하지 않습니다. 시도 : 대신

.replace(/[ ]{2,}/gi," "); /*{2,}=repeated*/ 
.replace(/(^\s*)|(\s*$)/gi,""); 

:

.replace(/\s+/g, " ") 
.replace(/^\s+|\s+$/g, ""); 

하고 잘 작동합니다.