user550265
user550265

Reputation: 3289

Character count using 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.

Upvotes: 41

Views: 125181

Answers (3)

Johannes
Johannes

Reputation: 67768

Since none of the given answers to this question has worked for me (I ask myself if jQuery has changed in this regard somehow?), I am adding the solution that does work in my case, i.e. using $('#myelement').text().length; to determine the number of characters inside a tag (defined by tag name or id).

var x = $('h1').text().length;
console.log(x);
$('#solution').text(x);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>How many characters are in this H1?</h1>
<p>This is just some more text.</p>
<p style="font-size: 1.4em;">Solution: There are <span id="solution"></span> characters in the h1 tag, including spaces</p>

Upvotes: 0

thomas
thomas

Reputation: 915

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

Upvotes: 2

Rion Williams
Rion Williams

Reputation: 76557

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.

Upvotes: 114

Related Questions