3 回答

TA貢獻(xiàn)1830條經(jīng)驗 獲得超9個贊
我使用Boolean速記''來過濾掉split.
const allText = document.body.innerText;
const allWords = allText.split(/\s/).filter(Boolean);
const numWords = allWords.length;
document.querySelector('#demo').innerHTML = numWords;
<h2>My First Web Page</h2>
<p>My First Paragraph.</p>
<p id="demo" />

TA貢獻(xiàn)1765條經(jīng)驗 獲得超5個贊
您可以用來HTMLElement.innerText
獲取網(wǎng)頁的文本。然后,您可以使用模式通過空格字符將字符串拆分為數(shù)組。那么字符串的長度應(yīng)該是你的字?jǐn)?shù)。
document.getElementById("demo").innerHTML?=?document.body.innerText.split(/\s/).length

TA貢獻(xiàn)1862條經(jīng)驗 獲得超7個贊
如果使用 javascript 需要innerTextthensplit(/\s/).filter(Boolean)
為什么使用過濾器(布爾)? 在 javascript 中,檢測有效單詞非常重要。
嘗試一下,如果你只使用 likeinnerText.split(/\s/).length會得到不同的計數(shù)。
這個例子是 JavaScript
document.getElementById("demo").innerHTML = document.getElementById("counted").innerText.split(/\s/).filter(Boolean).length
<!DOCTYPE html>
<html>
<body>
<div id="counted">
<h2>My First Web Page</h2>
<p>My First Paragraph.</p>
</div>
<p id="demo"></p>
</body>
</html>
jQuery 示例,還有
var length = $("#counted").text().trim().replace(/[\s]+/g, " ").split(" ").length;
$('#demo').html(length);
<!DOCTYPE html>
<html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<body>
<div id="counted">
<h2>My First Web Page</h2>
<p>My First Paragraph.</p>
</div>
<p id="demo"></p>
</body>
</html>
添加回答
舉報