How do I check if string contains substring? [duplicate]

Like this:

if (str.indexOf("Yes") >= 0)

…or you can use the tilde operator:

if (~str.indexOf("Yes"))

This works because indexOf() returns -1 if the string wasn’t found at all.

Note that this is case-sensitive.
If you want a case-insensitive search, you can write

if (str.toLowerCase().indexOf("yes") >= 0)


if (/yes/i.test(str))

The latter is a regular expression or regex.

Regex breakdown:

  • / indicates this is a regex
  • yes means that the regex will find those exact characters in that exact order
  • / ends the regex
  • i sets the regex as case-insensitive
  • .test(str) determines if the regular expression matches str
    To sum it up, it means it will see if it can find the letters y, e, and s in that exact order, case-insensitively, in the variable str

Leave a Comment