Or press ESC to close.

How to count characters in jQuery

19 Aug 2022 4 Min read
jQuery logo

This article explains how to count characters in a given string with the Jquery library and shows example methods with example functions and template code.

What is jQuery?

JQuery is a JavaScript library that was created by John Resig in 2006. The purpose of jQuery is to make the use of JavaScript much easier by implementing methods for common JavaScript tasks so the user can use these functions instead of writing them from scratch and save time.

How to Install jQuery?

In order to install and start using jQuery you have a couple of ways to accomplish this. One of the easiest ways is to include the following script to your html template so the browser automatically downloads all the library from the cdn and makes it ready for you to use it.

To Install jQuery and use it with your JavaScript paste the following script tag right before the end of </head> portion in your html document.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js>](<https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js>)"> </script>

"Be aware , the best practice is to frequently check jQuery for the latest released version and update it."

Counting characters in a string with jQuery

In order to count characters in a string variable with name "string" in jQuery we use the string.length method and it returns us the number of characters in a given string.

Example Code

let string = "Hello World";
let stringLength = string.length;
console.log(stringLength)

In the code above, we can see that there is a string variable named string and between the quotes it says "Hello World". When assigned the length of the string using string.length method to our new variable named stringLength , we can read the outcome using the console.log() method and it returns us the total character amount in "Hello World" which is 11.

It is because the blank space between the words that are not visible to our code editor is also considered a character as well, it is just not Alphanumeric like we are used to using in the normal world.

How To Only Return Alphanumeric Characters in A String?

To accomplish this mission , we have to somehow remove all the blank spaces in a string, be left with only alphanumeric characters and then read the character length with the string.length method.

To replace blank spaces with -no spaces- we use the .replaceAll() method. This method takes 2 parameters , in our case , what we want to replace in a string, which is a blank space and what we want to replace it with, which is not a space. So we want to replace " " with "" .

Lets see the example code below.

var string = "Hello world",

var stringWithoutSpace = string.replaceAll(" " , "");

// our string does not have space now
console.log(stringWithoutSpace);

// reading the length
console.log(stringWithoutSpace.length)

When we see the console, it logs: "HelloWorld", which is a string with blank space(s) removed. and now when we count the characters with the .length method, it will give us the number we first expected: 10.

In our example with a textarea, knowing how to remove blank spaces will come in handy.

Counting Characters In A String With Regular Expressions Using Javascript

Another method for counting characters in a string is to use the regular expression (regex). Regular expression comes in handy because you can determine exactly what kind of pattern you want the string to match, for example; match letters, from a-z, ignoring uppercase and white-space.

var string = "Hello, world";

var regex = /[a-z]/ig; // only count letters , without whitespace , from a-z ignoring uppercase

console.log(string.match(regex)); // prints 10 to the console

Counting Characters In A String Using A For Loop

Again, we can use a for loop to iterate over the length of the string and increment a counter for each iteration, thus giving us the total length of the string.

var string = "Hello, world";

var count = 0;

for (var i = 0; i < string.length; i++) {

   count++;

}

console.log(count); // prints 12 to the console

Since we did not exclude any white-space or commas, it will iterate over all characters including whitespace and comma so the output count is 12.

Counting Characters In A TextArea With Jquery

In this next demonstration we will see how to count characters in a textarea element. Textarea is a html element that allows the user to input text. We use the .val() method to have access to the input value of the textArea and we will read the user input (string) written in the textarea element.

For this interactive demonstration we will create a small application with a button and a textarea , our script will create references to both button and textarea , it will listen to the click event on the button by the user with the Jquery .click() method.

When the user clicks on the button , script will read the user input in the textArea element with the .val() method, remove excess spaces from the beginning and at the end of the string with the .trim() method and it will replace white-space with the replaceAll() method so we won't be counting white-space but only the characters.

Finally it will print the character length on the html document.

Here Is The Full Example Code

To use this example at home, create a text file named example.html and paste the following code in it. Open the file and open the developer console of your browser so you can see the results.

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>Counting Characters In A String With JQuery</title>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"> </script>

</head>

<body>

<!-- adding h1 to print the results -->

<h1 id="result_holder"></h1>

<!-- adding our textarea to our html document -->

<textarea id="example_test_area"></textarea>

<!-- adding our button -->

<button id="counter_button">Count Characters</button>

<script type="text/javascript">

window.onload = function(){

// creating a reference to the textArea with the "example_test_area"

var textArea = $("#example_test_area");

// creating a reference to the button with the "counter_button"

var counterButton = $("#counter_button");

// attaching click event handler to the button so

counterButton.click(function() {

// when user clicks on the button this portion of the script will execute //

// retrieving the user input with the .val() method and assinging it to variable called userText

var userText = textArea.val();

// removing excess space around our string with the .trim() method

userText = userText.trim();

// removing all white-space from the string with .replaceAll() method

userText = userText.replaceAll( " " , "" );

// retrieving the character count of our modified string with the .length method

// creating a reference to our H1 element so we can print the result inside

var resultHolder = $("#result_holder");

// printing the result by manipulating the text content

resultHolder.text(`User Input Has ${userText.length} Characters`);

});

}

</script>

</body>

</html>

Counting Words In A String With JQuery

Now from the perspective of the computer there is no such a thing as a "word" computer sees any string as a combination of characters, so let's define a word as a "combination of characters that are separated with white spaces".

So in our code we will split our string to chunks that are left after blanks and we use the .split(" ") method to split strings with the given parameter. In our case, a blank space will give us an array

Here is the code

let string = "Hello World";

let words = string.split(" ");

console.log(words);

// returns ["Hello","World"]

// to get the length of this array

console.log(words.length)

// outputs: 2

Now since our goal is to count the individual words, we need to know the amount of items that this array holds, and to do this, once again, we use the .length method to read the length of this array variable with the name "words" and the output is 2.

Counting Words In A TextArea With JQuery

Like our first example, when we want to count the words in a text area, we must get the textarea first, read the user input, create an array by splitting the string by the blank spaces and read the length by calling the .length method.

Be careful, some users may leave extra spaces in the beginning or at the end of their text, this will result in our script reading more "words" then we expect it to.

In such cases, we use the .trim() method to remove all blank spaces from the beginning and at the end of the string.

To add some interaction to this demonstration we will introduce a new html tag: button.

Full Html Example

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>Counting Words In A String With JQuery</title>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"> </script>

</head>

<body>

<!-- adding our textarea to our html document -->

<textarea id="example_test_area"></textarea>

<!-- adding our button -->

<button id="counter_button">Count Words</button>

<script type="text/javascript">

window.onload = function(){

// creating a reference to our textArea with the id "example_text_area"

var textArea = $("#example_test_area");

// creating a reference to our button with id "counter_button"

var counterButton = $("#counter_button");

// attaching a click event handler to our button

counterButton.click( function( event ) {

// when user clicks on the button , this portion of our script will execute, contained with the { }

// creating a variable named wordLength to store our word count

// getting the input value of our textArea by .val()

// removing possible the blank spaces from the end and at the beginning of the user by .trim()

// splitting the output string by blank spaces so we get an array of the items

// getting the length of the array by .length method

var wordLength = textArea.val().trim().split(" ").length;

// outputs the word count

console.log(wordLength);

});

}

</script>

</body>

</html>