代码之家  ›  专栏  ›  技术社区  ›  ITGuru

JS计算空格

  •  3
  • ITGuru  · 技术社区  · 6 年前

    我必须在字符串中找到空格,这包括enter、制表符和使用Javascript的空格。我有这个代码来查找空格

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

    这很好,并给出了总空间数。

    问题是,如果空格/回车/制表符相邻,我希望它只计数一次。我无法解决这个问题,希望能得到一些帮助或指出正确的方向。

    谢谢,古斯塔夫

    4 回复  |  直到 6 年前
        1
  •  3
  •   Stéphane Ammar    6 年前

    您可以在 split :

    var spaceCount = (string.split(/\s+/gi).length - 1);
    
        2
  •  2
  •   Nick Louloudakis    6 年前

    使用regex来实现这一点。 例如,您可以检查一个或多个制表符、空格或换行符的匹配数,并使用它们的计数。

    正则表达式规则是: [\t\s\n]+ -这意味着一个或多个制表符、空格或换行符符合规则。

    对于JavaScript:

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

    Regex是一种非常有效的方法。或者,您必须通过对象手动迭代,并尝试匹配存在一个或多个空格、制表符或换行符的情况。

    考虑一下,您试图做的是在编译器中使用,以便将特定字符序列识别为特定元素,称为标记。这种做法被称为 词法分析 ,或标记化。由于regex存在,因此无需手动执行此检查,除非您想执行一些非常高级或特定的操作。

        3
  •  1
  •   Swann    6 年前

    这是一个丑陋的解决方案,没有使用任何正则表达式,从性能上看,它是最优的,但它可以变得更具python风格。

    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!"))
    
        4
  •  1
  •   OverCoder    6 年前

    Stéphane Ammar's solution 这可能是最简单的,但如果你想要更高性能的东西:

    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;
    }