How To Count The Number Of Characters Without Spaces in jQuery

By Saruque Ahamed Mollick

In this post, we gonna learn how to count characters without spaces in jQuery. It’s quite easy to do so. Follow the steps I’m gonna mention here.

  1. Create a textbox area. ( or you can choose any div element or paragraph tag from where you gonna count the text, here in this example I am gonna count the live characters without space from a textbox area )
  2. Include jQuery.
  3. Create a jQuery function to achieve your goal.

Also Read,



Alert Before Leaving A Web Page Using JavaScript jQuery

Create  smooth scroll to top button in jQuery

 

Count Characters without Spaces in jQuery

Below is the code.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
        <script>
            $(function () {
                $('#id_of_your_text_area').keyup(function () {
                    var count = $(this).val().replace(/\s+/g, '').length;
                    $('#id_of_your_div_where_your_gonna_print_it').text(count);

                });
            });
        </script>

The full code be will like this

<html>
     <head>
          <title> Your Title here</title>
     </head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script> 
$(function () { 
$('#txtbox').keyup(function () { 
var count = $(this).val().replace(/\s+/g, '').length; 
$('#count_result').text(count); 
}); 
}); 
</script>
<body>
<div>
<input style="padding: 7px;" maxlength="60" size="50" type="text" id="txtbox" />

            <p>No. of characters without spaces is <span id="count_result"></span></p>
        </div>
</body>
</html>

The keyup function is triggered when the key is released.
replace(/\s+/g, ”) this method is used to remove the spaces from the typed text.

length is used to determine the number of characters after invoking the replace method (to remove empty spaces )

$(‘#count_result’).text(count);  is to assign the number of characters to the span id count_result.

<p>No. of characters without spaces is <span id=”count_result”></span></p>

here we gonna get the number of characters of the text area without spaces.

Also Read,

Calculate the distance between mouse and element in jQuery

Upload File With Ajax Using PHP and jQuery

Leave a Reply

Your email address will not be published. Required fields are marked *