mardi 24 octobre 2017

Look for keywords in a string in JS

I have an input field where I expect users to type text that contains 1 of many keywords that will trigger different audio files depending on the keyword. (I know that's not really smart from UX point of view but that's just a mockup/demo of a virtual assistant).

I'm using this code but I feel I can do much better, can you suggest some alternatives?

    keyword1 = "music";
    keyword2 = "news";
    keyword3 = "weather";
    keyword4 = "cooking";
    keyword5 = "pasta";
    keyword6 = "tech";

    if(text.search(keyword1)!=-1) {
      audio.src = a_music;
      audio.play();
    } else if(text.search(keyword2)!=-1){
      audio.src = a_news;
      audio.play();
    } 
   [...]
  }

Aucun commentaire:

Enregistrer un commentaire