skip to Main Content

I want to check if a variable is in any of a set of words. For example

'Guava'.match(/b(apple|mango|orange)b/ig);

The above does not match, which is correct.

'AppleA'.match(/b(apple|mango|orange)b/ig)

This too does not match. Again correct.

'Apple.A'.match(/b(apple|mango|orange)b/ig)

This however returns a match, which is not what I want. How do I fix this?

I want a match only if the value is Apple OR apple OR mango OR mAngo, etc.

2

Answers


  1. Try this

    'Apple.A'.match(/^(apple|mango|orange)$/ig)

    enter image description here

    Login or Signup to reply.
  2. To check if a string is one of several strings in JavaScript, case-insensitively, you can convert the string to lowercase with the toLowerCase method, and pass it to the includes method of the array of several strings to check against:

    console.log(['apple', 'mango', 'orange'].includes('Apple.A'.toLowerCase()));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search