- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
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 Articles
- Finding number of spaces in a string JavaScript
- Removing all spaces from a string using JavaScript
- Find longest string in array (excluding spaces) JavaScript
- 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?
- Reversing a string while maintaining the position of spaces in JavaScript
- C++ Program to Find the Number of Vowels, Consonants, Digits and White Spaces in a String
- C++ program to remove spaces from a string using String stream
- Swapping string case using a binary number in JavaScript
- C program to remove spaces in a sentence using string concepts.
- Find the Number of Substrings of a String using C++
- How to replace multiple spaces in a string using a single space using Java regex?
- Repeating string for specific number of times using JavaScript
- Sum of individual even and odd digits in a string number using JavaScript

Advertisements