LoginSignup
1
0

More than 3 years have passed since last update.

【JavaScript】英単語数をカウントする

Posted at

わりと簡単に作れると思っていましたが、
スペースがあったときに1カウントとすると、スペースが2つ続いたときも1単語としてカウントされてしまうことに頭を悩ませました。

解決策

HTML

<textarea id="count-area"></textarea>
<span id="output"></span>

JavaScript

const input = document.getElementById('count-area');
input.addEventListener('keyup', countWords);

function countWords() {
  // \S+の意味は「空白、タブ、改行以外が1回以上続く」
  const spaces = input.value.match(/\S+/g);

  let words;
  if (spaces) {
    words = spaces.length;
  } else {
    words = 0;
  }

  document.getElementById('output').textContent = words + " words";
}

参考

Count words as user type - Textarea and Javascript (Youtube)
正規表現入門 レッスン7 Space (Youtube)

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0