References

Beginner-friendly references for web development, with live, editable examples.

The JavaScript string.startsWith() method

Method JavaScript All modern browsers Updated
Quick answer

The startsWith() method checks whether a string begins with a given substring and returns true or false. "https://site.com".startsWith("https") is true. It's clearer than slicing or a regex, and its mirror endsWith() checks the end. The match is case-sensitive.

Overview

startsWith() tells you whether a string opens with some text. It returns a clean boolean, which makes it far more readable than the old workarounds — str.slice(0, 5) === "https" or a regex anchored with ^. Checking for a protocol, a prefix, a country code, a feature flag: this is the method.

An optional second argument lets you check from a given position rather than the very start, which is occasionally useful when scanning a longer string. The comparison is case-sensitive, so lowercase both sides first if case shouldn't matter.

Its natural partner is endsWith(), which checks the tail of the string — perfect for file extensions (name.endsWith(".pdf")). For a match anywhere in the string rather than at an edge, use includes().

Syntax

const yes = str.startsWith(searchString)
const yes = str.startsWith(searchString, position)

Parameters

The string.startsWith() method accepts the following parameters.

Parameter Description
searchString The text to test for at the start. Case-sensitive.
position Optional. The index to treat as the start of the string. Defaults to 0.

Example

Live example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
  const url = 'https://codeshack.io';

  document.getElementById('out').textContent =
    'secure? ' + url.startsWith('https') + '\n' +
    'is pdf? ' + url.endsWith('.pdf');
  // secure? true / is pdf? false
</script>

Best practices

  • Use startsWith() instead of slicing or a ^ regex for prefix checks — it states intent.
  • Use endsWith() for suffixes like file extensions.
  • Lowercase both strings for a case-insensitive check.
  • For a match anywhere, not just the start, use includes().

Frequently asked questions

How do I check if a string starts with something?
Use str.startsWith("prefix"), which returns true or false.
How do I check if a string ends with something?
Use str.endsWith("suffix") — for example name.endsWith(".pdf").
Is startsWith() case-sensitive?
Yes. Lowercase both the string and the search text if you need to ignore case.
What is the difference between startsWith() and includes()?
startsWith() only matches at the beginning; includes() matches anywhere in the string.