How to count the number of character in a string using jQuery

AuthorHariom Prajapati

Pubish Date19 Jun 2022

categoryJQuery

In this tutorial we will see that how to count the number of character in a string using jQuery.

let's see two examples to count the number of character in a string using jQuery.

1) Count the number of character with space in a string using jQuery

<!DOCTYPE html>
<html>
<head>
    <title>How to count the number of characters with space in a string 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 

php

 

2) Count the number of character without space in a string using jQuery

<!DOCTYPE html>
<html>
<head>
    <title>How to count the number of characters without in a string 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 

php

Comments 0

Leave a comment