search
String.prototype.startsWith
Returns true if the string begins with searchString at the given position (default 0). Added in ES2015 and is more efficient than slice() + === comparisons.
str.startsWith(searchString[, position]) Parameters
| Parameter | Purpose |
|---|---|
| searchString | Prefix to test against |
| position | Index to treat as the start of the string (default 0) |
Examples
console.log('https://example.com'.startsWith('https://')); Prints true
console.log('hello world'.startsWith('world', 6)); Prints true
console.log('Hello'.startsWith('hello')); Prints false (case-sensitive)
console.log('abc'.startsWith('')); Prints true
Gotcha
Throws TypeError if searchString is a RegExp. Case-sensitive — normalize casing beforehand if you need loose matching.
Related methods
String.prototype.endsWith
Returns true if the string ends with searchString when considered up to endPosition (default str.length). Useful for file extension and suffix checks.
String.prototype.includes
Returns true if searchString appears anywhere in the string, otherwise false. Added in ES2015 as a cleaner boolean alternative to indexOf() !== -1.
String.prototype.indexOf
Returns the index of the first occurrence of searchValue within the string, or -1 if not found. Search is case-sensitive and starts from fromIndex (default 0).
String.prototype.match
Runs a regular expression against the string and returns match information. With the g flag it returns an array of all match strings; without it, an exec-style array with capture groups, index, and input (or null).
String.prototype.matchAll
Returns an iterator of all detailed match results, each including capture groups, index, and input. Added in ES2020 and requires a global (g) RegExp — non-global patterns throw TypeError.