search

Home  >  Q&A  >  body text

Is it possible to check if part of a string matches one of multiple answers?

There are multiple answers to a question, is it possible to check if part of a given answer is correct using regular expressions and JavaScript?

For example, the English phrase "I think about it" can be translated into Esperanto "Mi pensas pri tio" or "< em>Mi pensas al tio”. When the user writes the answer, the input text should turn red if there are any errors. For example, entering "Mi pensas" is correct.

Is it possible to use a pattern like "Mi pensas (pri|al) tio" instead of looping through all possible answers?

P粉786800174P粉786800174470 days ago639

reply all(1)I'll reply

  • P粉563446579

    P粉5634465792023-09-11 20:04:08

    If I understand correctly, this is the approach I would take:

    function checkInput(input) {
      const pattern = /^Mi pensas( (pri|al) tio)?$/;
      return pattern.test(input);
    }
    
    console.log(checkInput("Mi pensas pri tio"));  // true
    console.log(checkInput("Mi pensas al tio"));  // true
    console.log(checkInput("Mi pensas"));  // true

    When the text is wrong, you can set it to red.

    reply
    0
  • Cancelreply