- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Finding the number of words in a string JavaScript
We are required to write a JavaScript function that takes in a string of any length. The function should then count the number of words in that string.
Example
const str = 'THis is an example string'; const findWords = (str = '') => { if(!str.length){ return 0; }; let count = 1; for(let i = 0; i < str.length; i++){ if(str[i] === ' '){ count++; }; }; return count; }; console.log(findWords(str));
Output
And the output in the console will be −
5
Advertisements