在 JS 中查找字符串中的关键字

Gus*_*epo 2 javascript if-statement substring cycle text-search

我有一个输入字段,我希望用户在其中输入包含许多关键字之一的文本,这些关键字将根据关键字触发不同的音频文件。(我知道从 UX 的角度来看这不是很聪明,但这只是虚拟助手的模型/演示)。

我正在使用此代码,但我觉得我可以做得更好,您能提出一些替代方案吗?

    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();
    } 
   [...]
  }
Run Code Online (Sandbox Code Playgroud)

cyr*_*r_x 5

您可以使用关键字 askey和文件 url as创建一个对象,value然后遍历键以检查文本是否与关键字匹配。

const config = { 
  'music': 'musicUrl',
  'news': 'newsUrl',
  'weather': 'weatherUrl',
  'cooking': 'cookingUrl',
  'pasta': 'pastaUrl',
  'tech': 'techUrl'
};

function match(input, obj) {
  var matched = Object.keys(obj).find(key => input.toLowerCase().search(key) > -1);
  return obj[matched] || null;
}

console.log(match('cats weather dogs', config));
console.log(match('cats tech dogs', config));
console.log(match('cats dogs', config));
Run Code Online (Sandbox Code Playgroud)