Want to find the number of characters in a string using jQuery? Use jQuery .length
property can be used to get or find out the number of characters in a string. You can also use this property to calculate the number of elements in a jQuery object.
Copy below example code and execute it to see the real time output.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Find Length of a String Using jQuery</title> <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ var myStr = $("textarea").val(); if($(this).hasClass("with-space")){ var withSpace = myStr.length; alert(withSpace); } else if($(this).hasClass("trimmed-space")){ var trimmedSpace = $.trim(myStr).length; alert(trimmedSpace); } else if($(this).hasClass("without-space")){ var withoutSpace = myStr.replace(/ /g,'').length; alert(withoutSpace); } }); }); </script> </head> <body> <h3>Enter Text and Click the Buttons</h3> <textarea rows="5" cols="60"> Paragraph of text with multiple white spaces before and after. </textarea> <br> <button type="button" class="with-space">Length of string including white-spaces</button> <br> <button type="button" class="trimmed-space">Length of string after removing beginning and trailing white-spaces</button> <br> <button type="button" class="without-space">Length of string without white-spaces</button> </body> </html> |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.