

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Find number of spaces in a string using JavaScript
There exists more than one way of finding this using JavaScript like by using the split() method, by using the for loop, by mapping and filtering, by using regex.
The way that makes use of regex is by far the most efficient and most performant method than the others, especially for big chunks of text. So we will be using that to solve this problem.
Following is the code −
Example
console.log(("abc def rr tt".match(/ /g) || []).length); console.log(("a f fe fg gsd f".match(/ /g) || []).length);
Note that we used an empty array with the OR operator to make sure that if the string does not contain any space instead of throwing error it should output 0.
Output
Output in the console will be −
3 5
- Related Questions & Answers
- Finding number of spaces in a string JavaScript
- Removing all spaces from a string using JavaScript
- Find longest string in array (excluding spaces) JavaScript
- How to find the number of spaces in a string vector in R?
- Summing numbers present in a string separated by spaces using JavaScript
- Breaking a string into chunks of defined length and removing spaces using JavaScript
- Remove extra spaces in string JavaScript?
- C++ Program to Find the Number of Vowels, Consonants, Digits and White Spaces in a String
- Reversing a string while maintaining the position of spaces in JavaScript
- Find the Number of Substrings of a String using C++
- Program to find number of different integers in a string using Python
- Swapping string case using a binary number in JavaScript
- C program to remove spaces in a sentence using string concepts.
- Repeating string for specific number of times using JavaScript
- How to replace multiple spaces in a string using a single space using Java regex?
Advertisements