使用另一个数组中数组的值来解析句子

时间:2018-07-22 18:27:03

标签: javascript chatbot string-parsing sentence

我正在创建一个聊天机器人,我需要帮助,我在Google上搜索了很多,但没有任何帮助。

我想做这样的事情:

var input = $('#InputField').html(); //consider it as hi, how are you!

var commonGreetings = ["hi", "hello"];
var questions  = [{commonGreetings} +",how are you!"]; // i want to check if first word of sentence is in the array named commonGreetings.

//然后

var answers  = ["i am fine, thank you!"];

    if(questions.indexOf(input ) > -1){
        $('#output').html(answers[0]);
    }

2 个答案:

答案 0 :(得分:0)

  1. 使用不区分大小写的匹配对输入进行正则表达式
  2. 使用Array.includes(matched.toLowerCase()

const input = "  Hello World!"

const commonGreetings = ["hi", "hello"]
const rx = /^\s*(\w+)/
const m = rx.exec(input, 'i')
if (m) {
  const found = m[1].toLowerCase()
  if (commonGreetings.includes(found)) {
    console.log(`Found a match for ${found}`)
  }
}

答案 1 :(得分:0)

  1. 第一个解决方案:

    var firstWord = input.match(/\w*/)[0];
    if(commonGreetings.indexOf(firstWord) > -1){
        $('#output').html(answers[0]);
    }
    
  2. 或者,您可以使用map方法来生成这样的问题数组:

    var questions = commonGreetings.map(function(commonGreeting) {
        return commonGreeting + ', how are you!'
    });