JavaScriptStrings

String.prototype.startsWith()

Checks whether a string starts with the given text. Returns true or false.

Returns
true if the string starts with the given text, false otherwise.
Changes the original
No
On this page

Example

#
JavaScript
const link = 'https://example.com/courses'

console.log(link.startsWith('https://'))
console.log(link.startsWith('http://'))
console.log(link.startsWith('HTTPS'))
Console
true
false
false

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

#
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 to 0.

More examples

#
Commands in a chat
JavaScript
const messages = ['/help', 'Hello everyone!', '/leaderboard']

for (const message of messages) {
  if (message.startsWith('/')) {
    console.log('Command:', message.slice(1))
  }
}
Console
Command: help
Command: leaderboard
Checking from a chosen position
JavaScript
const taskId = 'JS-2026-loops'

console.log(taskId.startsWith('2026', 3))
console.log(taskId.startsWith('loops', 8))
Console
true
true

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("/") returns false.
  • To check several possible prefixes, combine the method with some(): ["http://", "https://"].some((prefix) => link.startsWith(prefix)).

Related entries

#

Spotted a mistake or missing an example? Write to us.