使用 jquery 计算字符数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4661481/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:40:00  来源:igfitidea点击:

character count using jquery

jquery

提问by user550265

How can i count the number of characters in a textbox using jquery?

如何使用 jquery 计算文本框中的字符数?

$("#id").val().length < 3

$("#id").val().length < 3

just counts upto 3 character spaces but not the number of characters

最多只计算 3 个字符空格,但不计算字符数

回答by Rion Williams

For length including white-space:

对于包括空格的长度:

$("#id").val().length

$("#id").val().length

For length without white-space:

对于没有空格的长度:

$("#id").val().replace(/ /g,'').length

For removing only beginning and trailing white-space:

仅删除开头和结尾的空格:

$.trim($("#test").val()).length

For example, the string " t e s t "would evaluate as:

例如,字符串" t e s t "将评估为:

//" t e s t "
$("#id").val(); 

//Example 1
$("#id").val().length; //Returns 9
//Example 2
$("#id").val().replace(/ /g,'').length; //Returns 4
//Example 3
$.trim($("#test").val()).length; //Returns 7

Hereis a demo using all of them.

是一个使用所有这些的演示。