Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท String

String.prototype.startsWith()

Reference for JavaScript String.prototype.startsWith(): check whether a string begins with given text, optionally from a position, and why regular expressions throw.

The startsWith() method returns true if a string begins with the characters of another string, and false otherwise. It replaces the older idiom str.indexOf(prefix) === 0 and the less efficient str.slice(0, prefix.length) === prefix.

The comparison is case-sensitive. An optional second argument lets you test for the text at a specific position instead of at the very beginning.

JavaScript
"https://example.com".startsWith("https"); // true

Try it

JS Checking prefixes

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS No regular expressions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
string.startsWith(searchString)
string.startsWith(searchString, position)
Name Description
searchString The text to look for. It is converted to a string. A regular expression is rejected with a TypeError.
position Optional index at which to start comparing. Default 0. It is converted to an integer and clamped to the range from 0 to the string length.

Return value: true if the characters of searchString appear at position, otherwise false.

Exceptions: a TypeError if searchString is a regular expression.

Usage notes

  • Case-sensitive. Convert both sides with toLowerCase() for a case-insensitive check, keeping in mind the Unicode caveats of case conversion.
  • Empty string always matches: "abc".startsWith("") is true, and so it is at any position.
  • Regular expressions are refused on purpose, to avoid confusion over whether the pattern is treated literally. Use /^pattern/.test(str) when you need a pattern.
  • Non-strings are converted: "123".startsWith(12) is true, but null becomes the text "null". This can hide bugs, so pass strings.
  • Position is in UTF-16 code units. A negative position is treated as 0; a position past the end finds nothing except an empty search text.
  • Mirror image: endsWith() checks the end, and includes() checks anywhere.
  • Multiple prefixes: combine with Array.prototype.some(), as in the second example.
  • Not locale-aware. Comparison is by code unit, so composed and decomposed forms of an accented letter differ unless you normalize() first.

Browser support

String.prototype.startsWith() is supported in all current browsers. It was added in ES2015, so only very old browsers lack it.