Count Spaces in String using JavaScript: Different Approaches.

0

In this blog post you’ll learn how to detect and count the spaces present in the string using JavaScript. We’ll see various approaches to achieve this task.


detect and count the spaces present in a string using JavaScript


JavaScript Method Used:

Match()
Split()
Join()
Replace()
Test()
includes()


Also used for loop and regular expression.


Approach 1: Match() Method.

The match method is used to find matches within a string based on a provided pattern. We'll use regular expressions to match spaces within a string. 


See the code below.


JavaScript


    let string = "Good morning welcome to maketechstuff.com";
    console.log("string: ", string);
    console.log("No. of spaces: ", string.match(/[\s]/g).length);
  

Output:



Output when the string is empty:


If the string is empty the match method returns the error of null, Because the string is empty.


This approach gives a null error when the string contains no spaces. Means the match method returns the matches in a form of array, Here When no matches found the array will be null. So we get the null error.


To solve this, we can add a condition before calculating the number of spaces and after we get the matched in a form of array. We can first check if the array is empty or null, If not null only then proceed with counting the spaces.


See below code.


JavaScript


    let string = "Good morning welcome to maketechstuff.com";
    console.log("string: ", string);
    let spaces = 0;
    let array = string.match(/[\s]/g);

    if (array != null) {
        spaces = array.length;
    } else {
        spaces = 0;
    }

    if (spaces > 0) {
        console.log("Output: ", "Their are spaces. The number of spaces is: ", spaces);
    } else {
        console.log("Output: ", "Their are no spaces. The number of spaces is: ", spaces);
    }

  

Output:


count the number of spaces in a string


Approach 2: Split() Method and For loop.

  1. Split the string into characters array by split() method.
  2. Then, Define a variable with name space_count to store the space count with initial value 0.
  3. Iterate through each character in the string using a for loop to process each character one by one.
  4. Check if the current character is a space by comparing the character to a space character (" ").
  5. If the character is a space, add 1 to the space_count variable.
  6. After iterating through all characters, the space_count variable will hold the total number of spaces in the string.

If the space_count variable is more than 0. Means the string contains the space. If 0 then the string does not have space.


See below code.


JavaScript


    let string = "Good morning welcome to maketechstuff.com";
    console.log("string: ", string);
    let array = string.split("");
    let space_count = 0;
    for (let i = 0; i < array.length; i++) {
        const element = array[i];
        if (element == " ") {
            space_count++;
        }
    }
    if (space_count > 0) {
        console.log("Output: ", "The number of spaces are: ", space_count);
    } else {
        console.log("Output: ", "The number of spaces are: ", space_count);
    }
  

Output:


count the number of string with split method, match method and for loop


Approach 3: With regular expression and test() method.

A test method typically returns true or false. In this example, we'll create a method that checks for spaces in a string. The method will return true if the string contains at least one space, and false otherwise. After the method confirms the presence of spaces then we’ll count the spaces. 


As we are counting the spaces with the match method. The match method returns matches in a form of array. If no spaces are there in a string the match method returns a null error. So it's better to first check for a presence of at least one space before counting the spaces present in a string.


See below code.


JavaScript


    let string = "Hello welcome to maketechstuff.com";
    console.log("string: ", string);
    let space_check = /[\s]/g.test(string);
    console.log(space_check);

    // Counting the number of spaces only if their is a space in a string.
    if(space_check == true){
        console.log(string.match(/[\s]/g).length)
    }
  

Output:


count the spaces of string if present

Approach 4: Includes() Method.

Includes method return true or false based on search value according to search value. We'll search for space in a string. If the space is their, the method return true, otherwise it return false. If it return true we'll count it by match method with regular expression.


See the code below.


JavaScript


    let string = "Good morning welcom to maketechstuff.com";
    console.log("string: ", string);
    // Detect spaces with includes method.
    let space_check = string.includes(" ");
    console.log("Space check :", space_check);

    // Counting the number of spaces only if their is a space in a string.
    if (space_check == true) {
        console.log("No. of spaces :", string.match(/[\s]/g).length)
    }
    
    // Output:
    // string:  Good morning welcome to maketechstuff.com
    // Space check : true
    // No. of spaces : 4
    
  


So that's how you can count the number of spaces in a string using JavaScript. If you have any questions or suggestions, feel free to ask in the comment section.


You may like:

  1. Count the words present in string using JavaScript.
  2. Count the characters of string using JavaScript.
  3. Create the simple words counter and characters counter using JavaScript.
  4. Check if string contains the number using JavaScript.
  5. Check if string contains only the numeric values using JavaScript.
  6. Check if string contains the special characters in JavaScript.
  7. Make input field that replace multiple spaces between words to single space using JavaScript.

Tags

Post a Comment

0Comments

Share your thoughts.

Post a Comment (0)
To Top