includes() String Method in JavaScript
Guide to javascript string includes(): syntax, examples, case-sensitivity, start position, and differences from indexOf.
Drake Nguyen
Founder · System Architect
javascript string includes()
The javascript string includes() method (String.prototype.includes) provides a simple, readable way to check whether one string contains another. It returns a boolean: true when the substring is found and false otherwise. This ES6 string method is commonly used when you need to test if a string contains a given substring in JavaScript.
Syntax
str.includes(searchString[, position])
Parameters:
- searchString — the substring you want to find.
- position (optional) — the index at which to start searching (default is 0).
Basic example
var word = "bravery";
console.log(word.includes("rave")); // true
Case sensitivity
The includes() method is case-sensitive. That means "hi" and "Hi" are different:
const greetings = "Hi Sammy ~";
console.log(greetings.includes("hi")); // false
console.log(greetings.includes("Hi")); // true
Ignoring case
To check if a javascript string contains a substring regardless of case, normalize both strings first:
const haystack = "JavaScript Rocks";
const needle = "javascript";
console.log(haystack.toLowerCase().includes(needle.toLowerCase())); // true
Start position parameter
You can supply a start index to search from a specific position in the string:
const phrase = "hello world";
console.log(phrase.includes("world", 6)); // true
console.log(phrase.includes("world", 7)); // false
Difference between includes() and indexOf()
- includes() — returns a boolean (true/false). Easier to read when you only need to know existence (js includes string).
- indexOf() — returns the index of the substring or -1 if not found. Useful when you need the position.
When to use includes()
- Quick checks to determine if one string contains another (javascript string contains).
- Readable conditional checks: if (str.includes(substr)) { ... }
- When you want a boolean result without handling -1 from indexOf.
Related string search methods
- String.prototype.indexOf()
- String.prototype.startsWith()
- String.prototype.endsWith()
- RegExp methods: test(), match(), search()
Note: includes() was added in ES6 (ECMAScript 2015). For older environments, include a polyfill or use indexOf() for compatibility.
Quick reference examples
// String.prototype.includes() example
const s = "Learn to search within a string";
console.log(s.includes("search")); // true
// includes() with a start position
console.log(s.includes("Learn", 1)); // false
// javascript includes substring example (case-insensitive)
console.log(s.toLowerCase().includes("SEARCH".toLowerCase())); // true