使用jQuery的字和字符数 [英] Word and Character Count using jQuery

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

问题描述

我一直在寻找使用jQuery将文字和字符数添加到textarea,但我发现所有的插件都是限制字符和单词的。



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

有没有一种简单的方法可以检查字和字符?

解决方案

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 * \\\
/)。length};} var textarea = document.getElementById(text); var result = document.getElementById(result) ; textarea.addEventListener(input,function(){var v = wordCount(this.value); result.innerHTML =(< br>字符(无空格):+ v.charactersNoSpaces +< br>字符(和空格):+ v.characters +< br>文字:+ v.words +< br>行:+ v.lines);},false);

em> jsFiddle演示


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 v = wordCount( this.value );
  result.innerHTML = (
      "<br>Characters (no spaces):  "+ v.charactersNoSpaces +
      "<br>Characters (and spaces): "+ v.characters +
      "<br>Words: "+ v.words +
      "<br>Lines: "+ v.lines
  );
}, false);

<textarea id="text"></textarea>
<div id="result"></div>

jsFiddle demo

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

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