Javascript:在文本区域查找关键字的数量



输入:

var text = $('#id_textarea').val();
var keywords = $('#id_keywords').val().split(',');

输出:text 中的keywords数量

示例:

text = "jquery javascript js jquery-js js django python, blah blah blah...";
keywords = ['jquery', 'js'];
// so result = 3

感谢您的帮助:(

UPDATE:我需要一个函数来获得结果作为输出。谢谢

未经测试,逻辑应该可以工作。

var textParts = text.split(' ');
var count = 0;
for (var index = 0; index < keywords.length; index++) {
    for (var i = 0; i < textParts.length; i++) {
        if (textParts[i].match(keywords[index])) {
            count++; // found match, increment count
        }
    }
}
alert(count); // alert the amount of matches found

编辑

我测试了这个,结果是5。

您必须测试它是否等于,而不是使用match()

if (textParts[i] == keywords[index]) { // works

请在此处查看它的实际操作。

最新更新