简体   繁体   English

JS计算空格

[英]JS counting blank spaces

I have to find blank spaces in a string, this includes enter, tabs and spaces using Javascript. 我必须在字符串中找到空格,这包括使用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 谢谢,古斯塔夫

Tou可以在您的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. 正则表达式规则是: [\\t\\s\\n]+ - 表示一个或多个选项卡,空格或换行符合规则。

For JavaScript: 对于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. 由于存在正则表达式,因此无需手动执行此检查,除非您要执行非常高级或特定的操作。

Here is an ugly solution without using any regex, performance wise it's optimal, but it could be made more pythonic. 这是一个丑陋的解决方案,没有使用任何正则表达式,性能明智它是最佳的,但它可以更加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: StéphaneAmmar的解决方案可能是最简单的解决方案 ,但如果你想要更高性能的东西:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM