Quantcast
Channel: Linux Guides, Tips and Tutorials | LinuxScrew
Viewing all articles
Browse latest Browse all 314

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

$
0
0

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:

View the original article from LinuxScrew here: Javascript String includes() Method – Check if a String Contains Another String


Viewing all articles
Browse latest Browse all 314

Trending Articles