ITGuru
ITGuru

Reputation: 117

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

Upvotes: 3

Views: 2315

Answers (4)

OverCoder
OverCoder

Reputation: 1603

Stéphane Ammar's solution is probably the easiest on the eyes, but if you want something more performant:

function countGaps(str) {
    let gaps = 0;
    const isWhitespace = ch => ' \t\n\r\v'.indexOf(ch) > -1;

    for (let i = 0; i < str.length; i++)
        if (isWhitespace(str[i]) && !isWhitespace(str[i - 1]))
            ++gaps;

    return gaps;
}

Upvotes: 1

Swann
Swann

Reputation: 2473

Here is an ugly solution without using any regex, performance wise it's optimal, but it could be made more pythonic.

def countThis(s):
    count = 0
    i = 0
    while i < len(s):
        while i < len(s) and not s[i].isspace():
            i += 1
        if i < len(s):
            count += 1
            i += 1
        while i < len(s) and s[i].isspace():
            i += 1
    return count

print(countThis("str"))
print(countThis("   str   toto"))
print(countThis("Hello, world!"))

Upvotes: 1

Nick Louloudakis
Nick Louloudakis

Reputation: 6015

Use regex in order to achieve this. For instance, you could check how many matches of one or more tabs, spaces or newlines exist, and use their count.

The regex rule is : [\t\s\n]+ - meaning that one or more chuncks of tabs, spaces or newlines match the rule.

For JavaScript:

var test = "Test   Test        Test\nTest\nTest\n\n";
var spacesCount = test.split(/[\t\s\n]+/g).length - 1;
console.log(spacesCount);

Regex is a pretty efficient way of doing this. Alternatively, you would have to manually iterate via the object, and attempt to match the cases where one or multiple spaces, tabs, or newlines exist.

Consider that, what you are attempting to do, is used inside a compiler in order to recognize specific character sequences as specific elements, called tokens. This practice is called Lexical Analysis, or tokenization. Since regex exists, there is no need to perform this check manually, except if you want to do something very advanced or specific.

Upvotes: 2

St&#233;phane Ammar
St&#233;phane Ammar

Reputation: 1454

Tou can use regular expressions in your split:

var spaceCount = (string.split(/\s+/gi).length - 1);

Upvotes: 3

Related Questions