2

I want to make a basic AI chat in Javascript.

1) If a user says 'Hi, my name is Thore' I want to check what the closest match is with some predefined values.

My array looks like this:

const nameSentences = [`my name is`, `i'm`, `they call me`];

How can I check what the closest match is? In this example it should be the first value of my array.

2) The second part is how I can get the name out of the user input. Is it possible to predefine a place where the variable should stand?

Something like this

const nameSentences = [`my name is ${varName}`, `i'm ${varName}`, `they call me ${varName}`];

And afterwards substring the matching sentence with the user input to save the name the variable?

Thore
  • 1,918
  • 2
  • 25
  • 50
  • You can check each word of user input in sequence for matches. The most matches can be selected from array. Given the example the user name would be the word that is not matched, following the matched words. See [Javascript fuzzy search that makes sense](https://stackoverflow.com/questions/23305000/javascript-fuzzy-search-that-makes-sense/) – guest271314 Jul 18 '17 at 14:41
  • But 'Hi,' should also have no match. Should I add another array to filter away such words? – Thore Jul 18 '17 at 14:44
  • You can store the values in a database and use the FULL TEXT SEARCH feature. Otherwise you need some JS library to do similar job. – Racil Hilan Jul 18 '17 at 14:52
  • Not sure what you mean? What do you expect to occur with `"Hi,"` ? `"Hi,"` is not part of expected result at Question. At example `my name is` is matched in the input string `'Hi, my name is Thore'`. The two words and comma that are not matched can be referenced by indexes. – guest271314 Jul 18 '17 at 14:52

1 Answers1

4

You can save the different ways you would like to accept a name as Regular Expressions, with the capture for the name in the regular expression. You can get as robust as you'd like with it, but here is a starting point.

Once you find a match, you can stop iterating over the possible variations, you can take the match and output the name.

const nameSentences = [
  /i'm (\w+)/i,
  /my name is (\w+)/i,
  /they call me (\w+)/i
];

function learnName(input) {
  let match;
  for (let i = 0; i < nameSentences.length; i++) {
    match = input.match(nameSentences[i]);
    if (match) break;
  }

  if (match) {
    return `Hello, ${match[1]}. It's nice to meet you.`;
  } else {
    return `I didn't catch that, would you mind telling me your name again?`;
  }
}

console.log(learnName('Hi, my name is Thore.'));
console.log(learnName('They call me Bob.'));
console.log(learnName(`I'm Joe.`));
console.log(learnName(`Gibberish`));
KevBot
  • 17,900
  • 5
  • 50
  • 68