【问题标题】:Count occurance of a letter or a word in a sentence计算句子中字母或单词的出现次数
【发布时间】:2014-11-09 16:11:10
【问题描述】:

我想知道如何使用for 循环和递增的子字符串在整个文本中查找文本中的字符数,例如e

这是我目前得到的。

HTML:

<p id="paragraph"> this is the sentence, how many letters "e" can you find? How many "is" can you find</p>
<input type="text" id="text"/> <input type="button" value="search" onclick="search()"/>
<p id="howmany"></p>

JavaScript:

function search() {
  var letter = document.getElementById("text").value;
  var text = document.getElementById("paragraph").innerHTML; 
  var count = 0;
  var string = text.substring(0); 

  for(var i = 0; i < text.length, i++) {
    count++
  }
  document.getElementById("howmany").innerHTML = ("The result is" + count)
}

我只知道文本中有多少个字符,但我想找出文本中有多少个 eis 或任何内容。我知道有什么遗漏了,但是什么?

【问题讨论】:

  • 你真的需要阅读javascript,没有getElementsByIdinnerHtml等,也没有clickOn,基本上每一行代码都有错误写好了!

标签: javascript for-loop count substring


【解决方案1】:

这不需要循环 - 您只需使用正则表达式并计算匹配项:

string.match(/e/g).length
string.match(/is/g).length

也就是说,您的代码中还有很多其他错误:

function search() {
  var letter = document.getElementById("text").value;
  var text = document.getElementById("paragraph").innerHTML; 
  var count = 0;
  var string = text.substring(0,text.lenght); // should be length; or else not needed at all

  for(var i = 0; i < text.length, i++) {
    count++ 
  }
  document.getElementsById("howmany").innerHtml = ("The result is" + count) // it's getElementById, not getElements; it's innerHTML, not innerHtml
}

另外:onclickclickOn

【讨论】:

    【解决方案2】:

    我对这个问题的看法:

    function howMany () {
      var needle = document.getElementById('text').value.trim(),
          textProp = 'textContent' in document ? 'textContent' : 'innerText',
          haystack = document.getElementById('paragraph')[textProp].trim(),
          result = haystack.match(new RegExp(needle, 'g'));
      document.getElementById('howmany')[textProp] = result ? result.length : 0;
    }
    
    document.querySelector('input[type=button]').addEventListener('click', howMany);
    #howmany::before {
      content: 'Matches found: ';
    }
    
    #howmany:empty::before {
      content: '';
    }
    <p id="paragraph">This is the sentence, how many letters "e" can you find? How many "is" can you find</p>
    <label>String to find: <input id="text" placeholder="what are you looking for?" /></label>
    <input type="button" value="search" />
    <p id="howmany"></p>

    参考资料:

    【讨论】:

      猜你喜欢
      • 2013-12-10
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      • 2012-01-06
      • 1970-01-01
      • 1970-01-01
      • 2021-12-27
      • 1970-01-01
      相关资源
      最近更新 更多