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

时间:2017-10-24 15:15:04

标签: javascript if-statement substring cycle text-search

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

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

    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();
    } 
   [...]
  }

5 个答案:

答案 0 :(得分:4)

您可以创建一个关键字为key且文件网址为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));




答案 1 :(得分:1)

您应该使用一组关键字,而不是每个单词使用一个不同的变量。然后它是一块蛋糕:



const keywords = ["music","news","weather","cooking","pasta","tech"]

const text = "let's play some music"

if( keywords.some(keyword => text.includes(keyword) )) {
    console.log("Found")
      // audio.src = a_music;
      // audio.play();
}




答案 2 :(得分:0)

也许是阵列?

var array = ["music", "news", "weather", "cooking", "pasta", "tech"];

for(var i = 0; i < array.length; i++){
    if(text.includes(array[i])){
    //do something with i
    break;
  }
}

答案 3 :(得分:0)

在这里使用正则表达式对我来说似乎是一个很好的方法

let keywords = {
  music: 'musicSample',
  news: 'newsSample',
  weather: 'weatherSample',
  cooking: 'cookingSample',
  pasta: 'pastaSample',
  tech: 'techSample'
}

function searchKeywords (text) {
  let keys = Object.keys(keywords)
  let re = new RegExp('(' + keys.join('|') + ')', 'g')
  
  return text.toLowerCase().match(re)
}

console.log(searchKeywords('I love music and tech'))

// Play the first encountered word or queue every word to play consecutively what you found
console.log(searchKeywords('Mama is cooking some pasta')[0])

答案 4 :(得分:0)

这是一个在字符串列表中搜索关键字的示例,该关键字允许当前关键字的顺序不明确。

var keywords = [
    'music',
    // 'news',
    // 'weather',
    // 'cooking',
    // 'pasta',
    'tech',
]

var source = [
    "Create a database and tables",
    "What is up with singing",
    "Why is it cold outside",
    "What time is it",
    "How can I set up an appointment",
    "How to make you're own music",
    "Combining music and technology",
]

function search(keywords, source) {
    var re = new RegExp('(' + keywords.join('|') + ')', 'g')
    var results = []
    for (var i = 0; i < source.length; i++) {
        const text = source[i];
        var result = text.toLowerCase().match(re)
        if (result != null || result != null) {
            results.push(text)
        }
    }
    return results
}

var results = search(keywords, source)

console.log(results)