String. prototype. startsWith()
Checks whether a string starts with the given text. Returns true or false.
- Returns
trueif the string starts with the given text,falseotherwise.- Changes the original
- No
Example
#const link = 'https://example.com/courses'
console.log(link.startsWith('https://'))
console.log(link.startsWith('http://'))
console.log(link.startsWith('HTTPS'))Definition and usage
#The startsWith() method compares the start of a string with the given piece of text and returns true when it matches. It is case-sensitive and does not accept regular expressions, only plain text.
It comes in handy for recognizing prefixes: a protocol in a URL (https://), an area code in a phone number, a command starting with / in a chat, or a category written at the start of an identifier.
The second argument shifts where the comparison starts. text.startsWith("abc", 5) checks whether the piece of text appears starting exactly at index 5.
Syntax
#string.startsWith(searchString)
string.startsWith(searchString, position)Parameters
#searchString
string
The text the string should start with.position
number, optional
The index where the comparison starts. Defaults to0.
More examples
#const messages = ['/help', 'Hello everyone!', '/leaderboard']
for (const message of messages) {
if (message.startsWith('/')) {
console.log('Command:', message.slice(1))
}
}const taskId = 'JS-2026-loops'
console.log(taskId.startsWith('2026', 3))
console.log(taskId.startsWith('loops', 8))Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- With user-supplied data, strip spaces first with
trim(), because" /help".startsWith("/")returnsfalse. - To check several possible prefixes, combine the method with
some():["http://", "https://"].some((prefix) => link.startsWith(prefix)).
Related entries
#- String.prototype.endsWith()Checks whether a string ends with the given text. Returns true or false.
- String.prototype.includes()Checks whether a string contains the given piece of text. Returns true or false, and is case-sensitive.
- String.prototype.indexOf()Returns the index of the first occurrence of the given text in a string, or -1 when it is not there.
- String.prototype.slice()Returns a portion of a string from a start index to an end index (not included). Supports negative indexes.
Spotted a mistake or missing an example? Write to us.