In this post, we will learn how to find the number of characters of a string using jQuery. So how we can do this, we will learn in this post.


How To Find The Number Of Characters Of A String Using jQuery ?


Find The Number Of Characters Of A String

To find the number of characters in a string we use  length  jQuery property. This property helps us to get or find out the number of characters. We can also use this property to calculate the number of elements in a jQuery object. So how this property works we will see in the given example.


<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>How To Find The Number Of Characters In A String Using jQuery ?</title>
</head>
<body>

<h1>Find The Number Of Characters</h1>

<p>Input text to get number of characters</p>

<textarea id="inputText" rows="10" cols="50"> Hello, This is an example text. </textarea>

<br><br>

<button type="button" id="btn1">With Whitespace</button>

<button type="button" id="btn2">Without Whitespace</button>

<button type="button" id="btn3">Exact Number Of Characters</button>


<!-- jQuery CDN -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>


<script>

$(document).ready(function(){

// get text form textarea
var str = $("#inputText").val();

//with all whitespace
$("#btn1").click(function () {
var length = str.length;
alert(length);
});

//removing beginning and ending whitespace
$("#btn2").click(function () {
var length = $.trim(str).length;
alert(length);
});

//exact number of characters after removing all whitespaces, comma and period(.)
$("#btn3").click(function () {
var length = str.replace(/[ ,.]/g,'').length;;
alert(length);
});

});

</script>
</body>
</html> code-box



Summary

In this post we learned how to find the number of characters of a string using jQuery. You try to make it yourself. I hope you make. If you face any problem, then comment and tell us. Keep visiting the blog to read more similar posts.    

Post a Comment

Previous Post Next Post