使用 JavaScript 進行字數統計

Shiv Yadav 2023年10月12日
  1. 在 JavaScript 中計算字串中的字數
  2. 使用正規表示式計算字串中的單詞
使用 JavaScript 進行字數統計

我們將在本教程中探索如何使用 JavaScript 和幾個真實示例來計算段落中的單詞。

有時,你可能需要在文字框中限制使用者輸入或通過兩種方式限制使用者輸入:字元數或單詞數。今天,我們將研究後者,即如何使用 JavaScript 計算字串中的單詞數。

在 JavaScript 中計算字串中的字數

我們將建立一個自定義 JavaScript 函式,該函式接受字串輸入並返回所提供字串中的單詞總數。讓我們看下面的例子。

程式碼:

function getWordCount(str) {
  return str.split(' ')
      .filter(function(n) {
        return n != ''
      })
      .length;
}

const sent = 'Hey how are you doing in upwork?';
console.log('Complete Sentence: ' + sent);
console.log('Total words: ' + getWordCount(sent));

輸出:

"Complete Sentence: Hey how are you doing in upwork?"
"Total words: 7"

執行程式碼

首先,我們用破碎的 JavaScript 字串方法在空格字元上拆分字串,生成一個字串陣列。然後我們使用 filter JavaScript 陣列方法過濾掉空字串,當一個系列包含兩個連續的空格時,可能會出現空字串。

最後,我們有一個單詞陣列(以及額外的問號),我們可以使用陣列長度屬性計算陣列中元素的數量。這告訴我們給定字串中有多少個單詞。

使用正規表示式計算字串中的單詞

我們在上一節中學習瞭如何通過拆分空格字元來計算字串中的所有單詞,並且我們能夠做到這一點。但是,如果原始字串在一行中有很多空格,我們必須過濾掉可能出現的任何空行。

我們將使用 Regex 在以下程式碼中修改前面的示例。

程式碼:

function getWordCount(str) {
  return str.trim().split(/\s+/).length;
}

const sent = 'Hey how are you doing in upwork?';
console.log('Complete Sentence: ' + sent);
console.log('Total words: ' + getWordCount(sent));

輸出:

"Complete Sentence: Hey how are you doing in upwork?"
"Total words: 7"

執行程式碼

使用拆分 JavaScript 字串技術可以更方便地計算字串中的單詞。我們使用 /s+/ 正規表示式將系列分隔為一個或多個空白字元。

通過這種方式,我們可以直接移動到所需的結果,而無需過濾掉空行。此外,s 模式匹配新的行和製表符,導致比簡單地檢查空格字元更健壯的開發。

下面是一個互動式示例,展示如何使用我們在前面區域中構建的獲取字數統計功能。讓我們看看下面的示例,它顯示了使用者在文字框中鍵入時的實時字數計數器。

程式碼:

const textArea = document.getElementById('description');
textArea.addEventListener('input', () => {
  var textLn = textArea.value;
  document.getElementById('countText').innerHTML =
      'Total words: ' + getWordCount(textLn);
});

function getWordCount(str) {
  return str.trim().split(/\s+/).length;
}

輸出:

實時字數計數器

實時演示

當使用者輸入文字框時,會出現一個實時計數器。如果你想限制輸入文字,你可以利用並擴充套件此示例以向使用者顯示訊息。

作者: Shiv Yadav
Shiv Yadav avatar Shiv Yadav avatar

Shiv is a self-driven and passionate Machine learning Learner who is innovative in application design, development, testing, and deployment and provides program requirements into sustainable advanced technical solutions through JavaScript, Python, and other programs for continuous improvement of AI technologies.

LinkedIn