String.prototype.includes(): find a substring (ES2015)
What youβll learn
Section titled βWhat youβll learnβ- What
includes()returns and how itspositionargument works. - The edge cases: the empty string, coercion, and the
TypeErrorfor a regular expression. - How to make substring checks case-insensitive and Unicode-safe.
- Why a substring match is not a word match, and which tool to use instead.
Summary
Section titled βSummaryβTL;DR: str.includes(searchString, position) returns true if searchString appears anywhere in str at or after position (default 0), and false otherwise. The match is exact and case-sensitive.
It was added in ECMAScript 2015 (ES6) and works in every current browser and server runtime (see Compatibility).
The problem it solves
Section titled βThe problem it solvesβBefore ES2015 you asked βdoes this string contain that text?β with indexOf(), which answers βwhere is it?β and makes you compare against -1. That comparison is easy to get wrong (> 0 misses a match at index 0).
Running the samples: save a sample as a .mjs file and run it with Node.js 22 (node sample.mjs), or paste it into a browser console. The outputs shown were produced with Node.js 22.23.
const note = 'Customer asked to expedite order ORD-1042 before Friday';
// Before ES2015: compare the index against -1.console.log(note.indexOf('expedite') !== -1); // true
// ES2015: say what you mean.console.log(note.includes('expedite')); // trueconsole.log(note.includes('Expedite')); // false: case-sensitiveconsole.log(note.includes('ORD-', 40)); // false: search starts at index 40How it works
Section titled βHow it worksβ// Fragment: signaturestr.includes(searchString)str.includes(searchString, position)The specification converts this to a string (throwing a TypeError for null or undefined), throws a TypeError if searchString is a regular expression, converts it to a string otherwise, clamps position between 0 and the length, and reports whether the substring occurs at or after that index. That explains every edge case:
console.log('abc'.includes('')); // true: the empty string is everywhereconsole.log('abc'.includes('', 99)); // true: position is clamped to the lengthconsole.log('abc'.includes('a', -5)); // true: negative position becomes 0console.log('null value'.includes(null)); // true: null is converted to "null"console.log('42 items'.includes(42)); // true: 42 is converted to "42"console.log('ORD-1042'.includes()); // false: searches for "undefined"
try { 'ORD-1042'.includes(/ORD/);} catch (error) { console.log(error.constructor.name, '-', error.message);}
try { String.prototype.includes.call(undefined, 'x');} catch (error) { console.log(error.constructor.name, '-', error.message);}
// Canonically equivalent strings with different code units do not match.const composed = 'CafΓ©'; // Γ© as one code pointconst decomposed = 'CafeΜ'; // e + combining acute accentconsole.log(composed.includes(decomposed)); // falseconsole.log(composed.normalize('NFC').includes(decomposed.normalize('NFC'))); // trueOutput:
truetruetruetruetruefalseTypeError - First argument to String.prototype.includes must not be a regular expressionTypeError - String.prototype.includes called on null or undefinedfalsetrueThe error messages are V8βs wording; other engines word them differently.
The TypeError for a RegExp is deliberate: the spec reserves that case so a future edition can give it a meaning, instead of silently searching for the text "/ORD/". The method is also generic, so String.prototype.includes.call(42, '4') returns true.
Realistic example
Section titled βRealistic exampleβOrdersPortal flags support notes that need a human. The terms are matched case-insensitively by folding both sides to the same Unicode form and case before calling includes:
// triage.mjs - flag OrdersPortal support notes that need a human.const URGENT_TERMS = ['refund', 'chargeback', 'cancel', 'damaged'];
// Normalize once: same Unicode form, same case.const fold = (text) => text.normalize('NFC').toLowerCase();
export function triage(notes) { return notes.map(({ orderId, text }) => { const folded = fold(text); const matched = URGENT_TERMS.filter((term) => folded.includes(term)); return { orderId, urgent: matched.length > 0, matched }; });}
const notes = [ { orderId: 'ORD-1041', text: 'Box arrived DAMAGED, customer wants a Refund.' }, { orderId: 'ORD-1042', text: 'Please expedite, gift for Friday.' }, { orderId: 'ORD-1043', text: 'Customer may cancel if not shipped by Monday.' }, { orderId: 'ORD-1044', text: 'Asked about the cancellation policy only.' },];
console.table(triage(notes));Output:
βββββββββββ¬βββββββββββββ¬βββββββββ¬βββββββββββββββββββββββββββ (index) β orderId β urgent β matched ββββββββββββΌβββββββββββββΌβββββββββΌββββββββββββββββββββββββββ€β 0 β 'ORD-1041' β true β [ 'refund', 'damaged' ] ββ 1 β 'ORD-1042' β false β [] ββ 2 β 'ORD-1043' β true β [ 'cancel' ] ββ 3 β 'ORD-1044' β true β [ 'cancel' ] ββββββββββββ΄βββββββββββββ΄βββββββββ΄ββββββββββββββββββββββββββORD-1044 is a false positive: βcancelβ is a substring of βcancellationβ. That is exactly what includes promises, and it is the most common surprise with it. The next section shows the fix.
Common mistakes
Section titled βCommon mistakesβ-
Expecting a word match.
includesmatches substrings, so'cancellation'.includes('cancel')istrue. When you need whole words, use a regular expression with word boundaries:const text = 'asked about the cancellation policy only.';console.log(text.includes('cancel')); // true: substring of "cancellation"console.log(/\bcancel\b/i.test(text)); // false: whole word only\bis defined in terms of\w, which is essentially ASCII letters, digits and_, so/\bcafΓ©\b/u.test('un cafΓ© noir')isfalse. For text beyond ASCII, split into words withIntl.Segmenterinstead. -
Forgetting it is case-sensitive. Fold both sides with
toLowerCase()(ortoLocaleLowerCase(locale)when the language is known: in Turkish,'TITLE'.toLocaleLowerCase('tr-TR')is'tΔ±tle'with a dotless i). -
Passing a RegExp. It throws a
TypeError. Useregex.test(str). -
Ignoring Unicode normalization. User input from different keyboards and platforms can encode βΓ©β as one or two code points. Call
normalize('NFC')on both sides before comparing. -
Using it for URLs, paths or email domains.
url.includes('example.test')is also true forhttps://example.test.attacker.test/. Parse the value first (new URL(url).hostname), or check the right end withstartsWith()orendsWith(). -
Confusing it with
Array.prototype.includes. On an array,includescompares whole elements (['cancel'].includes('can')isfalse); on a string, it looks for a substring.
When to use it and when not to
Section titled βWhen to use it and when not toβ| Need | Use |
|---|---|
| Does the text contain this exact substring? | str.includes(sub) |
| Where is the substring? | str.indexOf(sub) / str.lastIndexOf(sub) |
| Does it start or end with it? | startsWith() / endsWith() |
| Pattern, whole word, or case-insensitive without folding | /pattern/i.test(str) |
| Every match with its position | matchAll() |
| Is a value one of a list? | Array.prototype.includes() |
includes is a convenience with the same search semantics as indexOf; choose it whenever you only need a yes or no.
Compatibility
Section titled βCompatibilityβAccording to MDNβs browser compatibility data, String.prototype.includes is supported in Chrome 41, Edge 12, Firefox 40, Safari 9 (including iOS), Opera 28, Node.js 4.0.0, Deno 1.0 and Bun 1.0. Firefox 18 to 47 also shipped an earlier draft under the name contains, removed in Firefox 48. Internet Explorer never supported it; core-js provides a polyfill if you still target it.
TypeScript: declared in lib.es2015.core.d.ts as includes(searchString: string, position?: number): boolean. Any target or lib of ES2015 or later includes it.
Interview questions
Section titled βInterview questionsβ1. What is the difference between str.includes(x) and str.indexOf(x) !== -1?
None in the result: both search for the same substring. includes returns a boolean, reads as the intent, and throws a TypeError for a RegExp argument, whereas indexOf converts the RegExp to a string such as "/ORD/" and searches for that.
2. What do 'abc'.includes('') and 'abc'.includes(undefined) return?
true and false. The empty string occurs at every position. undefined is converted to the string "undefined", which does not occur in "abc".
3. How do you do a case-insensitive includes?
Fold both strings to the same case (and ideally the same Unicode normalization form) and then call includes, or use a regular expression with the i flag. If the pattern comes from user input, escape it first.
4. Senior scenario: OrdersPortalβs order search box filters 50,000 orders in the browser with includes, and staff complain it is slow and misses βcafΓ©β when they type βcafeβ. What do you change?
Precompute a folded search key per order once (lowercase; for accent-insensitive search, normalize('NFD') and strip marks with /\p{M}/gu), fold the query the same way, and debounce input. Keep includes for the per-order check. If requirements grow (ranking, typos, word matching), move search to the server or a search index.
Key takeaways
Section titled βKey takeawaysβincludes(ES2015) returnstruewhen a substring occurs at or afterposition, and nothing more.- It is case-sensitive, treats the empty string as always present, converts non-string arguments to strings, and throws on a RegExp.
- A substring is not a word: use word-boundary regular expressions or segmentation when that matters.
- Normalize case and Unicode form on both sides for human text, and parse URLs and emails instead of searching them.
Related pages
Section titled βRelated pagesβ- String.prototype.startsWith(): check the start of a string.
- String.prototype.endsWith(): check the end of a string.
- String.prototype.matchAll(): every regex match with groups and positions.
- Array.prototype.includes(): the array method with the same name and different semantics.
- Unicode support: code points, normalization and the
uflag. - Strings and Regular expressions: the basics.
- JavaScript interview questions