Check If a String Contains a Substring in JavaScript

Does your string contain ___? There’s a simple way to check. Here’s how to search strings for substrings like a pro.

Published Categorized as JavaScript, Web & Code

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());

By Dim Nikov

Editor of Maker's Aid. Part programmer, part marketer. Making things on the web and helping others do the same since the 2000s. Yes, I had Friendster and Myspace.

Leave a comment

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