Check whether user input contains a required token
Validate input
JavaScript · Function
String.prototype.includes() performs a case-sensitive substring search and reports whether the requested text occurs in a string. It returns a boolean and accepts an optional starting position.
Call includes() on a string with the text to find, optionally providing the zero-based position where searching should start. It returns a boolean and compares characters case-sensitively; the starting position is converted and constrained to the string’s bounds.
includes(searchString)
includes(searchString, position)| Name | Type | Description |
|---|---|---|
searchString | string | The string to look for within the receiver. It must not be a regular expression; other values are converted to strings. |
position | number | The zero-based position at which to begin searching. It defaults to 0. |
A boolean: true if the search string occurs at or after the starting position; otherwise false.
true when the substring is found and false otherwise.true, including when the source string itself is empty.undefined searches for the literal string "undefined".const text = "To be, or not to be, that is the question.";
console.log(text.includes("question")); // true
console.log(text.includes("TO BE")); // false
console.log(text.includes("be", 10)); // false
console.log(text.includes("")); // trueThe method performs a case-sensitive substring check and can begin searching at the supplied position.
Validate input
Filter text
Guard conditional logic
Search from an offset
String.prototype.includes() returns a boolean indicating whether a string contains the supplied substring. The comparison is case-sensitive, and an empty search string is considered present.
Follow-up: What happens when the search argument is a regular expression? It throws a TypeError rather than performing a pattern search.
The optional position argument specifies where the search begins and defaults to zero. It is converted to an integer-like value and constrained to the string’s valid range.
Follow-up: Does a position beyond the string length match an empty search string? Yes, because the empty string is found at the effective endpoint.
The method coerces non-regexp search values to strings. If the argument is omitted or is undefined, the searched value becomes the string "undefined".
Follow-up: How can a case-insensitive search be implemented? Convert both the source and search strings to the same case before calling includes().
String.prototype.endsWith()String.prototype.indexOf()String.prototype.match()String.prototype.startsWith()