计算单词和字符 [英] Count Words and Characters

查看:81
本文介绍了计算单词和字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找使用jQuery向文本区域添加单词和字符数的方法,尽管我发现的只是用于限制字符和单词的插件.

I've been looking to add a word and character count to a textarea using jQuery although all I've found are plugins to limit characters and words.

我想实时更新,以便用户每次添加字符或单词时,计数器都会更新.

I would like to update in real-time, so that every time a user adds a character, or a word, the counter updates.

有没有简单的方法来检查单词和字符?

Is there a simple way to check for words and characters?

推荐答案

function wordCount(val) {
  var wom = val.match(/\S+/g);
  return {
    charactersNoSpaces: val.replace(/\s+/g, '').length,
    characters: val.length,
    words: wom ? wom.length : 0,
    lines: val.split(/\r*\n/).length
  };
}


var textarea = document.getElementById('text');
var result = document.getElementById('result');

textarea.addEventListener('input', function() {
  var wc = wordCount(this.value);
  result.innerHTML = (`
   <br>Characters (no spaces):  ${wc.charactersNoSpaces}
   <br>Characters (and spaces): ${wc.characters}
   <br>Words: ${wc.words}
   <br>Lines: ${wc.lines}
  `);
});

<textarea id="text" cols="30" rows="4"></textarea>
<div id="result"></div>

这篇关于计算单词和字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆