Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS counting blank spaces

I have to find blank spaces in a string, this includes enter, tabs and spaces using Javascript. I have this code to find spaces

function countThis() {
    var string = document.getElementById("textt").value;
    var spaceCount = (string.split(" ").length - 1);
    document.getElementById("countRedundants").value = spaceCount;
}

This works fine, and gives me the total number of spaces.

The problem is, i want it to only count once, if the space/enter/tab is next to each other. I cant solve this and would appreciate some help or point in the right direction.

Thanks, Gustav

like image 725
ITGuru Avatar asked Jan 26 '26 04:01

ITGuru


1 Answers

Tou can use regular expressions in your split:

var spaceCount = (string.split(/\s+/gi).length - 1);
like image 195
Stéphane Ammar Avatar answered Jan 28 '26 18:01

Stéphane Ammar