微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何计算JavaScript中充满文本的div中某个单词出现的次数?

如何解决如何计算JavaScript中充满文本的div中某个单词出现的次数?

我正在尝试创建一个与按钮相关联的事件函数,当您在文本区域中输入短语后单击该按钮时,会计算该短语在文本中出现的次数(仅p个元素)并同时输出函数创建的span元素中的值(多少次)。

预期结果是这样的: enter image description here

这是我的html:

<body>
<div id="main">
<p>The Phoenix Suns are a professional basketball team based in Phoenix,Arizona. They are members of the ...</p>
<p>The Suns have been generally successful since they began play as an
 expansion team in 1968. In forty years of play they have posted ...</p>
<p>On January 22,1968,the NBA awarded expansion franchises to an ownership 
group from Phoenix and one from Milwaukee. ...</p>
<ul>
    <li>Richard L. Bloch,investment broker/real estate developer...</li> 
    <li>Karl Eller,outdoor advertising company owner and former...</li>
    <li>Donald Pitt,Tucson-based attorney;</li>
    <li>Don Diamond,Tucson-based real estate investor.</li>
</ul>
</div>

<p>
Page by Marty Stepp. <br />
Some (all) information taken from Wikipedia.
</p>
<hr />

<div>
Search for text:
<input id="searchtext" type="text"  /> 
<button id="searchbutton">Search</button>
</div>
</body>

这是我的js函数

function count_search(event){
let span = document.createElement('span');
span.setAttribute("id","output");
document.body.appendChild(span);
var searchPhrase = document.querySelector("#searchtext").value;
var main = document.querySelector("#main");
var mainParas = main.querySelectorAll(" p ").textContent;
document.getElementById("#output").innerHTML = 
          (mainParas.match(/searchPhrase/g)).length;
/*var times = (mainParas.match(/searchPhrase/g) || []).length;
var content = "Searched for the word '" + searchPhrase + "' for " + times + " 
times. "; 
document.getElementById("output").innerHTML = content; */
}

但是,结果不会显示。你能帮我么?任何建议都非常感谢!

解决方法

此代码可以为您提供帮助。它采用主div类型p的所有子元素,采用它们的内容并将它们连接为单个字符串。 然后,它将在该字符串中搜索在输入字段中输入的单词,并返回出现的次数。

使用带有两个修饰符的正则表达式完成单词搜索:g使搜索在第一个匹配项后继续,而i则忽略大写。

请注意当您输入“ dolor”时它如何返回2,因为dolor的第三次出现是在li元素中,而不是p

function search() {
    // Get the word to count
    var searchString = document.getElementById("input").value;
    var textDiv = document.getElementById("main");
    // Get all p elements in the main div
    var childNodes = textDiv.getElementsByTagName('p')
    // Store all text from the child elements in a single string
    var completetext = ""
    for(var i = 0; i < childNodes.length; i++) {
        completetext = completetext + childNodes[i].innerHTML
    }
    // Search the string and count the ocurrences
    var regEx = new RegExp(searchString,"gi");
    // When match() returns 0,replace it with an empty array
    // to make the length work in this case
    var count = (completetext.match(regEx) || []).length
    result.innerHTML = count;
}
<div id="main">
    <p>Lorem ipsum dolor sit amet. Lorem ipsum</p>
    <p>Lorem ipsum dolor sit amet. Lorem ipsum</p>
    <li>dolor sit amet.</li>
</div>
<input type="text" id="input">
<button id="button" onclick="search()">Search</button>
<span id="result">

,

world = geopandas.read_file(geopandas.datasets.get_path('naturalearth_lowres'))
southern_world = world.cx[:,:0]
western_world = world.cx[:0,:]
western_europe = world.cx[1:10,40:60]

所以它之所以没有出现是因为没有与按钮相关的onclick事件。以下代码应该会有所帮助。

,

您的方法几乎正确。在主div中拥有所有p之后,就可以遍历它们以获取其文本。然后,您可以将其追加到包含所有文本的字符串中,以便以后进行搜索。为此,使用您要搜索的值创建一个RegExp,最后使用match()找出字符串在文本中的出现时间。

function count_search() {
  var allText = "";

  var element = document.getElementById("output");
  element && element.parentNode.removeChild(element);

  let span = document.createElement('span');
  span.setAttribute("id","output");
  document.body.appendChild(span);

  var searchPhrase = document.querySelector("#searchtext").value;

  var mainParas = document.querySelectorAll("#main > p");

  mainParas.forEach(el => allText+= el.innerText);

  var regex = new RegExp(searchPhrase,"gi");
  var times = allText.match(regex);
  document.getElementById("output").innerHTML = times ? `How many times I searched for the word "${searchPhrase}": ${times.length}` : "No matches found";
}
<body>
  <div id="main">
    <p>The Phoenix Suns are a professional basketball team based in Phoenix,Arizona. They are members of the ...</p>
    <p>The Suns have been generally successful since they began play as an
    expansion team in 1968. In forty years of play they have posted ...</p>
    <p>On January 22,1968,the NBA awarded expansion franchises to an ownership 
    group from Phoenix and one from Milwaukee. ...</p>
    <ul>
      <li>Richard L. Bloch,investment broker/real estate developer...</li> 
      <li>Karl Eller,outdoor advertising company owner and former...</li>
      <li>Donald Pitt,Tucson-based attorney;</li>
      <li>Don Diamond,Tucson-based real estate investor.</li>
    </ul>
  </div>
  <p>
    Page by Marty Stepp. <br />
    Some (all) information taken from Wikipedia.
  </p>
  <hr />
  <div>
    Search for text:
    <input id="searchtext" type="text"  /> 
    <button id="searchbutton" onclick="count_search()">Search</button>
  </div>
</body>

,

这是一些执行此操作的JS

function count_search(event){
  let span = document.createElement('span');
  span.setAttribute("id","output");
  document.body.appendChild(span);
  var searchPhrase = document.querySelector("#searchtext").value;
  var main = document.querySelector("#main");
  var mainParas = main.querySelectorAll("p");
  mainParas = Array.from(mainParas)
  for (let i = 0; i<mainParas.length;i++) {
    mainParas[i] = mainParas[i].textContent
  }
  mainParas = mainParas.join(' ')
  words = mainParas.split(' ')
  count = 0;
  for (let i = 0; i<words.length;i++) {
    if (words[i] == searchPhrase) {
      count++
    }
  }
  document.getElementById("output").innerHTML = count
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。