2013-02-19 18 views
0

首先輸出:什麼是使用jQuery將html轉換爲文本並計算單詞的乾淨方式?

var postContent = wysihtml5Textarea.data("wysihtml5").editor.getValue(); 

看起來是這樣的:

<p>sf sdf asd asd <b>asd</b> d asd ad&nbsp; asd&nbsp;</p> 

我要做到以下幾點:

  1. 刪除所有的HTML標籤
  2. 刪除所有&nbsp;
  3. 計算單詞(例如a像「搖滾」這樣的詞應該算作一個單詞)。

我一直在瀏覽周圍SO,我發現以下幾點:

$(txt).text(); remove all HTML tags 
txt.replace(/&nbsp;/g, ''); // remove all &nbsp; 
txt.replace(/[^\w ]/g, "").split(/\s+/).length; // word count (not sure if it deals with hyphenated words) 
$('#word-count').html(wordCount); // and display it 

我不知道如何搭配這一切都在一個乾淨的方式。

有什麼建議嗎?

+0

檢查此鏈接http://jsfiddle.net/Pervez/YJVPZ/257/ – EnterJQ 2013-02-19 06:19:41

回答

1

嘗試使用此http://jsfiddle.net/adiioo7/QLgjs/1/

var str="<p>sf sdf asd asd <b>asd</b> d asd ad&nbsp; asd&nbsp;</p>"; 

alert("Plain Text : " + $(str).text()); 
alert("Word Count : " +$(str).text().split(" ").length); 
+0

感謝,但在'' 還在這裏。 – alexchenco 2013-02-19 09:10:16

+0

$(str).text()將自動返回純文本,不含html標籤和html字符,例如 請檢查演示小提琴。 – 2013-02-19 09:11:46

+0

好的,但奇怪的是,當我擊中空間時,計數器增加。所以空間,空間,空間都會計爲3. – alexchenco 2013-02-19 09:14:42

相關問題