How to count the white spaces in a string in Node.js

1 Answer

0 votes
function countWhitespaceCharacters(str) {
    let count = 0;
    const length = str.length;
     
    for (let i = 0; i < length; i++) {
        if (/\s/.test(str[i])) {
            count++;
        }
    }
     
    return count;
}
 
const str = "Node.js \n  Programming \r Language \t ";
 
console.log("Total white spaces: " + countWhitespaceCharacters(str));




/*
run:
  
Total white spaces: 10
           
*/

 



answered Oct 20, 2024 by avibootz

Related questions

1 answer 131 views
1 answer 132 views
1 answer 118 views
1 answer 127 views
1 answer 116 views
...