简体   繁体   中英

How to check if words are there in a string using switch statements?

I have this code -

  const myFunc = () => {
    switch (transcript) {
      case transcript.split(" ").includes("hello"):
      case transcript.split(" ").includes("hey"):
      case "hi":
      case "hallo":
        const greetingArray = ["Hello!", "Hi!"];
        const randomItem =
          greetingArray[Math.floor(Math.random() * greetingArray.length)];
        setMyVar(randomItem);
        TTS(myVar, "english");

        break;
      case "bye":
        TTS("Goodbye", "english");
        break;
    }

    return myVar;
  };

As you can see, I tried to check if the words hey and hello is there in the transcript, but it isn't working. How can I correct this?

Thanks in advance!!

.includes returns true/false so it would look like case true: case: false which is pointless code. It compiles (pseudo code) to something weird like this:

val = "hello";
if (val: string == (val.split(" ").includes("hello"): boolean) || val == "hi" || etc) {
   ... do set var stuff
} 

case "word": does work, however it would mean the transcript can ONLY and must be character by character identical to the "word".

So the includes do nothing, and because the following case's say "hallo" and "hi", hello/hey will not trigger any case and because theirs no default event it just escapes.

Your fix would be changing both your transcript.split.includes to simply "hello" and "hey".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM