简体   繁体   中英

Simple Way of Looking for Key Phrases in Jquery?

I have set up a method of retrieving messages from a real time chat client. I want to take these messages (a lot of text) and find out if any of these messages contain key phrases. If they contain a key phrase I will simply add 1 to a count variable.

Currently I am doing it like this ("good", "yes", and "nice" are the key phrases)

for (var i = 0; i < data.msgs.length; i++)
{
    str = data.msgs[i].msg.toLowerCase();
    if (str.search("good") != -1 || str.search("yes") != -1 || str.search("nice") != -1)
    {
         count = count + 1;
    }
}

This method works, but it isn't very pretty. I plan on adding around 100 different key phrases and it is easy to see that this will become silly. Also, adding new key phrases is annoying and cumbersome.

I'm wondering if there is a better way of making some kind of database of key phrases from which I can search for matches. Preferably one which allows for easy adding and deleting of phrases.

Thanks.

var keys = ['good', 'yes', 'nice'];
for (var i = 0; i < data.msgs.length; i++)
{
    str = data.msgs[i].msg.toLowerCase();
    for(var j=0; j < keys.length; j++){
         if(str.indexOf(keys[j]) !== -1){
            count++;
            //could also return here if you want to break the function after a find
          }
    }
}

You could also load your "keys" from a JSON file and parse it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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