Using a for loop
We will iterate through each character in the string and check if this character is a space or not. If yes, we will increment the count variable and finally print out this count result:
let string = " HELLO LEARNSHAREIT " // Initialize a count variable let count = 0 // Count the spaces in a string for (let i = 0; i < string.length; i++) if (string[i] == ' ') // Increment the count variable if this is a space count++ console.log(count)
The above example uses the for loop with i is initialized to 0 (the starting index of a string) and checks if each character is equaled to a whitespace or not. The result will be 4 because there are 4 spaces in the string, one at the beginning, one at the end, and two between the words HELLO and LEARNSHAREIT.
let string = " HELLO LEARNSHAREIT " // Count the spaces in a string let matches = string.match(/ /gi) console.log(matches.length)
As you can see, using this match() function will make your code appear shorter and simpler. However, remember that this method returns an array instead of a number of matches, so you must get the length (size) of this array to count the spaces in the string because each space is each match.
The second approach above only prints out the length property of the array. But this approach requires you to minus the result with 1 because the split() method returns an array of substrings separated by a given delimiter in its argument. Please take a look at its syntax and usage here.
let string = " HELLO LEARNSHAREIT " // Count the spaces in a string let array = string.split(/ /gi) console.log(array.length - 1)
The above example points out the whitespace characters in the regex (“/ /”) that requires global, case-insensitive search for the spaces in the string. The letter “g” after the slash indicates that it needs to find all the matching occurrences that appeared instead of the one that first appeared. However, you can easily replace the regex with a whitespace character because this method allows using it:
let string = " HELLO LEARNSHAREIT " // Count the spaces in a string let array = string.split(" ") console.log(array.length - 1)
As can be seen, using the split() method, you have to minus the length of the array with 1 as we have explained, this function does not return an array of matches. Instead, it returns an array of substrings separated by a separator, you can also print out the array to know what is inside it:
" HELLO LEARNSHAREIT ".split(" ")
['', 'HELLO', '', 'LEARNSHAREIT', '', '']
Maybe you are interested:
- Insert a Space before Capital Letters in a String in JS
Name of the university: HCMUT