Simple Way of Looking for Key Phrases in Jquery?

75 Views Asked by At

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.

1

There are 1 best solutions below

2
On BEST ANSWER
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.