Javascript String includes() Method – Check if a String Contains Another String

Javascript String includes

Here’s a guide on checking whether a string contains another string in the JavaScript programming language using the includes() method.

includes() Syntax

string.includes(search, start)

Note that:

  • string should be a string value or variable
  • search should be the string you are checking for
  • start is the index (position) you want to start searching at.
    • It’s optional
    • Indexes start counting at 0 – The first character of the string is at index 0 returns bool

Examples

var string = "Linux all over the world";
var result = string.includes("over"); // Will return TRUE
var result2 = string.includes("over", 15);// Will return FALSE

Note that the second example returns FALSE because we start the search at index 15, which is after the appearance of the string “over”.

Legacy Browser Support

The string.includes() method is not supported in Internet Explorer. If for some godforsaken reason, you must have support for IE, you can check the index of the string using the indexOf() method.

var string = "LinuxScrew";
var substring = "ew"; // The value to search for

var result = string.indexOf(substring) !== -1; // Will return TRUE

Note that:

  • string.indexOf() will return the index (position) of the substring.
    • Indexes start counting at position 0
  • If the substring is not found, indexOf() will return the value -1
  • So, to check if the string is present, the above example checks that the value returned from indexOf() is not equal to -1

Conclusion

Check out our other articles on working with strings in JavaScript:

SHARE:
nv-author-image

Brad Morton

I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Reply

Your email address will not be published. Required fields are marked *