最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JS counting blank spaces - Stack Overflow

programmeradmin2浏览0评论

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

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

Share Improve this question asked Jan 2, 2018 at 15:02 ITGuruITGuru 1172 silver badges12 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 3

Tou can use regular expressions in your split:

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

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 piler 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.

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!"))

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;
}
发布评论

评论列表(0)

  1. 暂无评论