Prefix validation
Validate a command or protocol marker before processing input.
JavaScript · Function
String.prototype.startsWith() checks whether a string begins with a specified string and returns a boolean. An optional position lets the check begin at a later index.
Call startsWith() on a string with the text to find and, optionally, an index where the check should begin. The method compares the characters from that position, converting non-regular-expression search values to strings, and returns a boolean; the optional position defaults to zero.
startsWith(searchString)
startsWith(searchString, position)| Name | Type | Description |
|---|---|---|
searchString | string | The characters to search for at the start of the string. Regular expressions are rejected; other values are converted to strings. |
position | number, optional | The index where the first character of searchString is expected. Defaults to 0. |
true if the specified characters are found at the beginning from the selected position, including for an empty search string; otherwise false.
const value = "Saturday night plans";
console.log(value.startsWith("Sat"));
console.log(value.startsWith("night", 9));
console.log(value.startsWith("sat"));Checks a prefix at the beginning of the string or from a specified starting index; matching is case-sensitive.
Validate a command or protocol marker before processing input.
Select records or routes whose identifiers share a known leading token.
Check a string from a known offset without creating a substring.
startsWith(searchString, position) returns true when the specified characters occur at the beginning of the string starting at position; otherwise it returns false. The position defaults to 0.
Follow-up: What happens with an empty search string? It returns true, including when the requested position is at or beyond the string's effective search range.
The method converts non-regex search values to strings, but rejects a regular expression with TypeError. Thus, startsWith(42) searches for "42", while startsWith(/42/) throws.
Follow-up: Why is a regular expression rejected? The method is a literal prefix comparison rather than a pattern-matching operation.
position identifies the index where the first character of searchString is expected. It is converted to an integer-like value and clamped between zero and the string length.
Follow-up: What is the result if the prefix would extend beyond the string's end? The method returns false unless the search string is empty.
String.prototype.endsWith()String.prototype.includes()String.prototype.indexOf()String.prototype.slice()