2012-05-18 57 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 

它給了我一個字數6,而不是3.任何想法爲什麼?我不擅長正則表達式!

感謝這麼多

+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

這些正則表達式是醜陋和冗餘。我的建議是做像得到清理HTML:通過簡單地用正則表達式

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

然後循環並增加一個計數器:

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

這是非常粗糙的(並使得大量的假設可能對你不適用)但是,A /你會得到「單詞」的數量[你必須處理的定義]和B /你不必替換在得到你所說的你想要的內容之前刪除大量的文本。

HTH

0

與 「更換空間」 並不worj這種方式。 嘗試:

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

代替:

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

,它應該工作的罰款。