Search code examples
javascriptarrayschatbot

JavaScript 2D array, if input RegEx match col1 , return col2


I trying to set up a chatbot which when user input match some word, then will response accordingly.

this works

  var input = "i love you";
  
  if(/.*cute.*/.test(input)) { alert("Aw.... so sweet");}
  if(/.*love.*/.test(input)) { alert("Love you too");}

//result "Love you too"

However, how can I put the data in an array and still make it works?

example:

var queryResponse = [ ["cute","Aw.... so sweet"],
                      ["love","Love you too"] ];

How do I modify this line?

 if(/.*  (what should i insert here?) .*/.test(input)) { alert(So that the response appear here?);}

Solution

  • index of each keys and value should match

    var keys=['cute','love'];
    var values= ['so cute', 'i love you'];
            
    for(var i = 0; i < keys.length ; i++){
            
       let re = new RegExp(`.*${keys[i]}*.`);
        
       if(re.test(input){
            alert(values[i]);
            break;
       }
    }