Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 number of spaces in a string JavaScript
We are required to write a JavaScript function that takes in a string containing spaces. The function should simply count the number of spaces present in that string.
For example −
If the input string is −
const str = 'this is a string';
Then the output should be −
const output = 4;
Example
const str = 'this is a string';
const countSpaces = (str = '') => {
let count = 0;
for(let i = 0;
i < str.length; i++){
const el = str[i];
if(el !== ' '){
continue; };
count++; };
return count;
};
console.log(countSpaces(str));
Output
This will produce the following output −
4
Advertisements