Logo

How to find the number of characters in a string using jQuery?

AuthorSumit Sarkar

Date25 Oct 2024

CategoryjQuery

In this tutorial, we will learn how to count the number of characters in a string using jQuery.

How to find the number of characters in a string using jQuery?

We will use the .length property to find the number of characters in the string, and also find the length of the string with space and without spaces.

Syntax -

string.length

Character count with space

In this example we will count the number of characters with space in a string using jQuery.

<!DOCTYPE html>
<html>
<head>
   <title>Count the number of characters in a string with space using jQuery</title>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>

<body>
<h1>Count the number of characters in a string with space using jQuery</h1>
<input type="text" name="string" value="welcome to teknowize" class="input2">
<button class="clkbutton">Click Me!</button>

 <script>
   $(document).ready(function(){ 
   $('.clkbutton').click(function(){
   var countInput = $('.input2').val().length;
   alert(countInput);
 });
});
</script> 

</body>
</html>

Output

Try it Yourself »
 

Character count without space

In this example we will count the number of character without space in a string using jQuery.

Example

<!DOCTYPE html>
<html>
<head>
   <title>Count the number of characters in a string without space using jQuery</title>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>

<body>
<h1>Count the number of characters in a string without space using jQuery</h1>
<input type="text" name="string" value="welcome to teknowize" class="input2">
<button class="clkbutton">Click Me!</button>
 <script>
   $(document).ready(function(){ 
   $('.clkbutton').click(function(){
   var countInput = $('.input2').val().replace(/ /g,'').length;
   alert(countInput);
 });
});
</script> 

</body>
</html>

Output

Try it Yourself »
 

Conclusion

jQuery's .length property provides a simple way to count characters in a string with and without spaces.
Comments 16

Leave a comment

Create Resume for free

Create a professional quality resume in minutes with free templates.

Create Resume
Resumes