split()
methodYou can calculate or find the number of words in a string using the JavaScript split()
method. This method simply split a string into an array of substrings by a specified character.
In the following example we have also used the trim()
method to remove the leading and trailing white spaces from the string before counting the numbers of words.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Count Number of Words in a String</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
var words = $.trim($("textarea").val()).split(" ");
alert(words.length);
});
});
</script>
</head>
<body>
<textarea cols="50">The quick brown fox jumps over the lazy dog.</textarea>
<br>
<button type="button">Count Words</button>
</body>
</html>
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on harsukh21@gmail.com
How to Remove a Specific Item from an Array in JavaScript
Use the splice() Method You can use t...How to add or remove rows inside a table dynamically using jQuery
Use the jQuery .append() or .remove() Me...How to Create Python Virtual Environments on Ubuntu 18.04
Python virtual environment is a self-con...Laravel 7 - Dynamically Add Input Fields using HandlebarsJs
Hello Artisan In this tutorial i will...How to Remove a Property from a JavaScript Object
Use the delete Operator You...