【问题标题】:Javascript simple word counterJavascript简单的单词计数器
【发布时间】:2021-05-10 19:51:55
【问题描述】:

我正在尝试为 Javascript 中的 textarea 元素制作一个简单的单词计数器。到目前为止,我已经尝试了很多方法,但每个人都失败了。我搜索了网络,但我只找到了使用我仍然不知道的函数或 JS 命令和语法的解决方案。目标是计算文本区域中最多包含 140 个字符的单词。文本也可以不止一行,所以我必须考虑换行符。 直到现在我写了这个:

for (let i = 0; i < text.length; i++) {
          if (text[i]==' ' && (text[i-1]!==' ' && text[i-1]!=='\n')) { 
            wc++;
            
          }
          else if(text[i]=='\n' && text[i-1]!==' '){
            wc++;
          }
        }

这有点用,但只有在我按空格键后才有效。有没有办法从用户只输入一个字母开始计数? 编辑: 我已经尝试过 .split(" ") 方法,但它不适用于 ENTER/RETURN 键。我的目标是在用户输入字母后立即开始计数。

【问题讨论】:

标签: javascript


【解决方案1】:

您可以将split 与空格的正则表达式一起使用

let words = text.split(/\W/);
wc = words.length;

split 将您的字符串分解为一个数组,每次找到您传递给它的表达式时,它都会在数组中创建一个新条目。

正则表达式 /\W/ 获取空格(' ' 和 '\n')

所以这样它会创建一个每个单词都分开的数组,然后你只需要检查数组的长度

【讨论】:

  • 我们的课程中还没有涉及正则表达式。还有其他方法吗?
  • 你可以做 text.spit(" ")
【解决方案2】:

添加了用单个空格替换所有多个空格。还添加了检查是否输入了新行。

document.getElementById("inputField").addEventListener("input", function(e) {
  // Get the input text value
    var text = this.value;

    //replace all multiple spaces with single space
    text = text.replace(/\s\s+/g, " ");
    // Initialize the word counter
    var wc = 0;

    // Loop through the text
    // and count spaces in it 
    for (let i = 0; i < text.length; i++) {
      if (text[i]==' ' && (text[i-1]!==' ' && text[i-1]!=='\n')) { 
        wc++;

      }
      else if(text[i]=='\n' && text[i-1]!==' '){
        wc++;
      }
    }

    // Display it as output
    document.getElementById("show").innerHTML = wc;
})
<textarea id="inputField" rows=10 cols="60">
</textarea>
<br><br>

<p> Word Count:
    <span id="show">0</span>
</p>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-30
    相关资源
    最近更新 更多