[英]Regex to remove white spaces, blank lines and final line break in Javascript
[英]Regex to to detect white spaces, new lines to count words in Javascript
我正在嘗試在Summernote編輯器中按角度計數單詞。 我創建了一項服務來統計單詞,但不適用於新行
這是示例文本
Hult International 23
s
e
r
t
我試圖通過以下方式做到這一點
if (text && text.length > 0) {
text = text.replace(/<(?:.|\n)*?>/gm, '').replace(/&nbsp;/g, '').replace(/ /g, '').trim();
return text.length ? text.split(/\s+/).length : 0;
}
您也可以在所附的圖片中看到它http://i.prntscr.com/rVnabSWbR1G5rcelz915qQ.png
String.prototype.countWords = function(){
return this.split(/\s+\b/).length;
}
現在,您可以使用text.countWords()
而無需使用替換功能。
您將\\n
替換為空字符串,從而刪除了行之間的所有空格,並從23sert
制作了一個單詞。 我不確定我是否知道replace
步驟的要點,但是如果您的文本中沒有非單詞符號,則可以使用return text && text.length ? text.split(/\\s+/gm).length : 0
return text && text.length ? text.split(/\\s+/gm).length : 0
而不是整個塊。
(可能需要打磨以解決前導/后部空間)
在對正則表達式結構進行了徹底研究之后,我在替換標簽的同時替換了空白並成功了
text = text.replace(/<(?:.|\n)*?>/gm, ' ').replace(/&nbsp;/g, '').replace(/ /g, '').trim();
發布此答案可能是對其他人有幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.