jQuery String Contains Functions

Sam Deering
Share

Finding whether a string contains another string can be achieved not using jQuery but plain ole JavaScript!

Here is how you do it.

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

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

if (str.toLowerCase().indexOf("yes") >= 0)
//OR
if (/yes/i.test(str))
//OR
//You could use search or match for this.
str.search( 'Yes' )

Another example to check if a string contains another string.

if (v.indexOf("http:") == -1) 
{
  //string doesn't contain http
}

This will return the position of the match, or -1 if it isn’t found.