Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Character count using jQuery

Tags:

jquery

How can I count the number of characters in a textbox using jQuery?

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

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

like image 929
user550265 Avatar asked Jan 11 '11 18:01

user550265


People also ask

How can I count the number of characters in a textbox using jQuery?

value. length; document. getElementById(displayto). innerHTML = len; } </script> <textarea id="data" cols="40" rows="5" onkeyup="countChars('data','charcount');" onkeydown="countChars('data','charcount');" onmouseout="countChars('data','charcount');"></textarea><br> <span id="charcount">0</span> characters entered.


2 Answers

For length including white-space:

$("#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 " $("#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 

Here is a demo using all of them.

like image 71
Rion Williams Avatar answered Sep 19 '22 08:09

Rion Williams


Use .length to count number of characters, and $.trim() function to remove spaces, and replace(/ /g,'') to replace multiple spaces with just one. Here is an example:

   var str = "      Hel  lo       ";    console.log(str.length);     console.log($.trim(str).length);     console.log(str.replace(/ /g,'').length);  

Output:

20 7 5 

Source: How to count number of characters in a string with JQuery

like image 28
thomas Avatar answered Sep 20 '22 08:09

thomas