String.prototype.startsWith
Checks whether a string starts with a given substring.
Available since: ES2015
Syntax
str.startsWith(searchString, position)Parameters
| Parameter | Type | Description |
|---|---|---|
| searchString | string | The expected beginning of the string. |
| position | number | Optional. The position where the check starts; defaults to 0. |
Return value
boolean`true` if the string starts with the substring, `false` otherwise.
Examples
Checking the protocol of a URL:
console.log('https://example.com'.startsWith('https://'));
console.log('http://example.com'.startsWith('https://'));Output:
true
falseThe companion endsWith() checks the end of a string:
console.log('photo.png'.endsWith('.png'));Output:
trueNotes
The comparison is case-sensitive.
See also
- String.prototype.includes — Checks whether a string contains a given substring.
- String.prototype.endsWith — Checks whether a string ends with the given text.
Related recipes
In the tutorial
- String methods — Useful string methods in JavaScript: finding a position, reading characters, padStart, repeat, split and join, method chains.