我正在创建一个聊天机器人,我需要帮助,我在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]);
}
答案 0 :(得分:0)
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)
第一个解决方案:
var firstWord = input.match(/\w*/)[0];
if(commonGreetings.indexOf(firstWord) > -1){
$('#output').html(answers[0]);
}
或者,您可以使用map
方法来生成这样的问题数组:
var questions = commonGreetings.map(function(commonGreeting) {
return commonGreeting + ', how are you!'
});