Suppose you want to check if a string (for example, “apples and oranges”) contains a substring (for example, “oranges”) in JavaScript. This tutorial will show you how to do this with two JavaScript methods, as well as how to handle the challenge of case sensitivity.
Using String.includes()
To check if a string contains a substring in JavaScript, you can use the string.includes()
method. The method will return a value of true
if the string includes the substring, and of false
if it doesn’t.
/* Declare string */
myString = "apples and oranges";
./* Check if string includes substring */
myString.includes("apples");
Note that the string.includes()
method is case-sensitive. To do a check regardless of whether the string contains uppercase or lowercase words, use the string.toLowerCase
method to convert it to lowercase.
/* Declare string */
myString = "apples and oranges";
/* Check if string includes substring */
myString.includes("Apples".toLowerCase());
Using String.indexOf()
Another way to check if a string contains a substring in JavaScript is to use the string.indexOf()
method. The method searches the string for the substring in question and returns the index of the first occurrence if there is one. If the substring isn’t contained in the string, the method will return -1
.
/* Declare string */
myString = "apples and oranges";
/* Check if string includes substring */
myString.indexOf("oranges");
Note that the string.indexOf()
method is case-sensitive. To do a check regardless of whether the string contains uppercase or lowercase words, use the string.toLowerCase()
method to convert it to lowercase.
/* Declare string */
myString = "apples and oranges";
/* Check if string includes substring */
myString.indexOf("Oranges".toLowerCase());