简体   繁体   English

文本区域中单词出现的指南

[英]Guide on word occurrence in a textarea

I have a Textarea box, a textbox and a button. 我有一个Textarea框,一个文本框和一个按钮。 I would like on clicking the button, for the word in the textbox to be checked against words in the textarea and count number of occurrence. 我想单击按钮,以便对照文本区域中的单词和出现次数来检查文本框中的单词。

I have tried last 2 days to write a click function to do this but not getting anywhere since not sure what codes or logic follows next. 我已经尝试了过去2天来编写一个click函数来执行此操作,但是由于不确定接下来要遵循的代码或逻辑,因此无法实现任何目标。 Only managed to read the contents in the textarea but not sure how to get the word in the textbox and search against sentence in textarea. 仅设法读取了文本区域中的内容,但不确定如何在文本框中获取单词并针对文本区域中的句子进行搜索。

Please I am a newbie in JQuery so not asking for anyone to write the code but more of a guide if possible. 请,我是JQuery的新手,所以不要求任何人编写代码,而是要求更多的指南。 If this question isn't permitted here, I am more than happy to delete it. 如果这里不允许这个问题,我很乐意将其删除。 Thanks 谢谢

Use string.match() along with processing to ensure the first string is not empty and that there actually is a match. string.match()与处理一起使用,以确保第一个字符串不为空并且确实存在匹配项。 Did the following in jQuery since you seemed interested in using it. 在jQuery中进行了以下操作,因为您似乎对使用它感兴趣。

var textVal = $('#textbox').val();
var textArea = $('#textarea').val();
var matching = new RegExp('\\b' + textVal + '\\b','g');             
var count = textArea.match(matching);
var result = 0;

if (count !== null) {
    result = count.length;
}

http://jsfiddle.net/promiseofcake/t8Lg9/3/ http://jsfiddle.net/promiseofcake/t8Lg9/3/

You are looking for string occurrences, so take a look at this thread . 您正在寻找字符串出现的地方,因此请看一下该线程

You could do this using match(), as suggested in the comments: 您可以使用match()来执行此操作,如注释中所建议:

var m = searchText.match(new RegExp(wordMatch.toString().replace(/(?=[.\\+*?[^\]$(){}\|])/g, "\\"), "ig"));
// m.length contains number of matches

But that will also match partial words, like 'fox' in 'foxy'. 但这也将匹配部分单词,例如“ foxy”中的“ fox”。 So another method is to split the input into words and walk over them one by one: 因此,另一种方法是将输入分成单词,然后逐个遍历它们:

var count = 0;
var words = searchText.split(' ');
for (x in words) {
    if (words[x].toLowerCase() == wordMatch) {
        count++;
    }
}

Take a look at this full example: http://jsfiddle.net/z7vzb/ 看一下完整的示例: http : //jsfiddle.net/z7vzb/

<input type="text"/>
<textarea>...</textarea>
<button>Get</button>
<div></div>
<script>
$("button").click(function(){
count=$("textarea").text().split($("input[type=text]").val()).length-1;
$("div").html(count);
})
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM