How to Check if String Contains Substring in JavaScript
In JavaScript, you can check if a string contains a substring using the
includes() method, which returns true if the substring is found and false otherwise. For example, str.includes(substring) checks if substring exists inside str.Syntax
The includes() method is called on a string and takes one required argument: the substring you want to find. It returns a boolean value: true if the substring is present, and false if not.
Optional second argument specifies the position to start searching from.
javascript
string.includes(substring, startPosition)
Example
This example shows how to check if the word "hello" is inside a string. It prints true if found, otherwise false.
javascript
const str = "Hello, world!"; const substring = "hello"; // includes() is case-sensitive const contains = str.includes(substring); console.log(contains); // false // To ignore case, convert both strings to lowercase const containsIgnoreCase = str.toLowerCase().includes(substring.toLowerCase()); console.log(containsIgnoreCase); // true
Output
false
true
Common Pitfalls
- Case sensitivity:
includes()is case-sensitive, so "Hello" and "hello" are different. - Older browsers:
includes()is not supported in very old browsers;indexOf()can be used instead. - Wrong usage: Using
includes()on non-string types will cause errors.
javascript
const str = "Hello, world!"; // Wrong: case-sensitive check console.log(str.includes("Hello")); // true console.log(str.includes("hello")); // false // Right: case-insensitive check console.log(str.toLowerCase().includes("hello")); // true // Legacy way using indexOf console.log(str.indexOf("hello") !== -1); // false console.log(str.toLowerCase().indexOf("hello") !== -1); // true
Output
true
false
true
false
true
Quick Reference
| Method | Description | Returns |
|---|---|---|
| includes(substring, startPosition) | Checks if substring exists in string starting at optional position | true or false |
| indexOf(substring) | Returns index of substring or -1 if not found | number (>=0 or -1) |
| toLowerCase() | Converts string to lowercase for case-insensitive checks | new lowercase string |
Key Takeaways
Use
includes() to check if a string contains a substring easily and clearly.includes() is case-sensitive; convert strings to lowercase for case-insensitive checks.For older browsers, use
indexOf() and check if the result is not -1.Always call
includes() on a string to avoid errors.The optional second argument in
includes() sets the start position for searching.