javascript 如何从javascript中的句子中搜索单词
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32431453/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Search a word from a sentence in javascript
提问by Makudex
I have this html code here:
我在这里有这个 html 代码:
<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>
and a javascript code here:
和这里的javascript代码:
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;
}
Now what I want to do here is that:
现在我想在这里做的是:
when the user inputs
woo
it would outputwood
together with the number of results found like -2 results found
.when the user inputs
od
it would also outputwood
together with the number of results found like -2 results found
.Same with
ch
- which the output should bechip, chop
-2 results found
.And with
op
- which the output should bechop
-1 result found
.
当用户输入时
woo
,它将wood
与找到的结果数量一起输出,例如 -2 results found
。当用户输入时,
od
它也会wood
与找到的结果数量一起输出,例如 -2 results found
。与
ch
- 输出应该是chip, chop
- 相同2 results found
。并且
op
- 输出应该是chop
-1 result found
。
回答by Yeldar Kurmangaliyev
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.
永远不要从onclick
HTML 属性调用函数,而是使用事件。请参考这个 SO question。我已经用 jQueryclick
函数替换了这个调用——如果你愿意,你可以使用 vanilla JS 方法。
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.
你的代码几乎可以工作了。您可以简单地使用 RegExpmatch
方法来查找字符串中出现的次数。您无需手动执行此操作。
This code works for me:
这段代码对我有用:
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.";
Here is the working JSFiddle Demo.
这是工作中的JSFiddle Demo。
回答by Yeldar Kurmangaliyev
I would prefer to break the sentence into words:
我更愿意把句子分成几个词:
var words = myString.split(' ');
Now filter the words which contain the text being sought:
现在过滤包含要查找的文本的单词:
words = words.filter(function(word) {
return word.indexOf(myWord) !== -1;
}
Then print them out or insert in the DOM or whatever:
然后将它们打印出来或插入 DOM 或其他任何内容:
result = words.join(',') + " - " + words.length + " result(s) found";
document.getElementById("demo".textContent = result;
回答by Roko C. Buljan
Here's a beast:
这是一只野兽:
var string = document.getElementById("str").innerHTML;
var elDemo = document.getElementById("demo");
function getPortions(queryString, string) {
var results = [];
if(queryString.length > 0){
var rgxp = new RegExp("(\S*)?("+ queryString +")(\S*)?", "ig");
string.replace(rgxp, function(match, , , ){
results.push( (||"") +"<b>"+ +"</b>"+ (||"") );
});
}
return results;
}
document.getElementById("txt1").addEventListener("input", function(){
var result = getPortions(this.value, string);
elDemo.innerHTML = "Found "+ result.length +" results<br>"+ result.join("<br>");
});
b{color:red;}
<p id="str">How much wood could a wood chip chop</p>
<input type="text" id="txt1"/>
<p id="demo">Found 0 results</p>
- it returns the results results length,
- bolded portions of characters,
- you don't need a Button to start the search.
- 它返回结果结果长度,
- 字符的粗体部分,
- 您不需要按钮来开始搜索。
Basically it's a remake of this answer: Truncate text preserving keywords
基本上它是这个答案的翻版:截断文本保留关键字
回答by yugi
try this one
试试这个
function myFunction()
{
var myString = document.getElementById("str").innerHTML;
var myWord = document.getElementById("txt1").value;
var myPattern = new RegExp(myWord,'g');
var myResult = myString.split(" ");
var innerHtmml="";
var count=0;
for(var i=0; i<myResult.length; i++) {
var result = myResult[i].match(myPattern);
if(result) {
alert(myResult[i]);
innerHtmml=myResult[i]+",";
count++;
}
}
document.getElementById("demo").innerHTML = myResult;
}