Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
67 views
in Technique[技术] by (71.8m points)

javascript find string from input

I made a chatbot in html/css/js using the switch method. I'm wondering how can I find a specific string from the user input. Any help is appreciated! example: usr input "what is the fee"

let theMsg = document.getElementById('theMsg');
let sendMsg = document.getElementById('sendMsg');
sendMsg.addEventListener('click', function(){
    userSend()
    switch(theMsg.value){
        case 'fee':
            feeResponse();
            break;
question from:https://stackoverflow.com/questions/65865520/javascript-find-string-from-input

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Create a dictionary Object where the propertyName is the keyword you're interested in for printing a desired message:

const responsesDictionary = {
  fee: "Fee is similar to Foo",
  bar: "Bar is almost like Baz",
  foo: "Foo is the grandad of Fee",
  "a z": "The alphabet",
};

const EL_theMsg  = document.querySelector("[name=theMsg]");
const EL_sendMsg = document.querySelector('#sendMsg');

const words = Object.keys(responsesDictionary).join("|");
const rgx = new RegExp(`\b(${words})\b`, "ig");

const getResponse = () => {
  const msg = EL_theMsg.value.toLowerCase();
  const matches = msg.match(rgx) || [];
  const response = matches.map(word => responsesDictionary[word]);
  console.log(response.join("
"));
};

EL_sendMsg.addEventListener("click", getResponse);
Insert some text and use one of the words: "fee", "bar" or "foo".<br>Hit SEND for some magic<br>

<input name="theMsg" type="text" value="Test default foo message bar">
<button id="sendMsg">SEND</button>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...