如何从javascript中的句子中搜索单词 [英] How to Search a word from a sentence in javascript

查看:40
本文介绍了如何从javascript中的句子中搜索单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里有这个 html 代码:

I have this html code here:

<p id = "str">How much wood could a wood chip chop</p>
<br>
<input type = "text" value = "" id = "txt1"/>
<button onclick = "myFunction()"> Search </button>

<p id="demo">Display the result here.</p>

和这里的 javascript 代码:

and a javascript code here:

function myFunction()
{
  var myString = document.getElementById("str").innerHTML;
  var myWord = document.getElementById("txt1").value;
  var myPattern = new RegExp('.'+myWord,'g');

  var myResult = myString.split(" ");

  for(var i=0; i<myResult.length; i++) {
    var result = myResult[i].match(myPattern);
    if(result) break;
  }

  document.getElementById("demo").innerHTML = myResult;

}

现在我想做的是:

  1. 当用户输入 woo 时,它会输出 wood 以及找到的结果数量,例如 - 2 results found.

  1. when the user inputs woo it would output wood together with the number of results found like - 2 results found.

当用户输入od 时,它也会输出wood 以及找到的结果数量,例如 - 2 results found.

when the user inputs od it would also output wood together with the number of results found like - 2 results found.

ch 相同 - 输出应为 chip,chop - 2 results found.

Same with ch - which the output should be chip, chop - 2 results found.

并且使用 op - 输出应该是 chop - 1 result found.

And with op - which the output should be chop - 1 result found.

推荐答案

永远不要从 onclick HTML 属性调用函数,而是使用事件.请参阅这个问题.我已经用 jQuery click 函数替换了这个调用 - 如果你愿意,你可以使用 vanilla JS 方法.

Never call functions from onclick HTML attribute, use events instead. Please, refer to this SO question. I have replaced this call with jQuery click function - you may use vanilla JS methods if you prefer.

您的代码几乎可以运行了.您可以简单地使用 RegExp match 方法来查找字符串中出现的次数.您无需手动执行此操作.

Your code is almost working. You can simply use RegExp match method to find count of occurences in a string. You don't need to do this manually.

此代码适用于我:

var myString = document.getElementById("str").innerHTML;
var myWord = document.getElementById("txt1").value;
var myPattern = new RegExp('(\\w*'+myWord+'\\w*)','gi');

var matches = myString.match(myPattern);

if (matches === null)
{
    document.getElementById("demo").innerHTML = "No results"; // Any message or empty
    return;
}

document.getElementById("demo").innerHTML = matches + " - " +  matches.length + " result(s) found.";

这是正在运行的 JSFiddle 演示.

这篇关于如何从javascript中的句子中搜索单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆