String.prototype.startsWith()
A prefix test that says what it means. It replaces both indexOf(x) === 0 and the anchored regex, and unlike the regex it needs no escaping.
Demo
The first two cases are the everyday use — distinguishing https from http is a prefix test, and writing it this way is both clearer and safer than a regex where the slashes and dots would need escaping. The fourth case shows the difference from includes: 'ell' is present in 'hello' but not at the beginning, so this returns false where includes would return true. As with includes, an empty search string is always true.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| searchString | string | yes | The prefix to test for. A RegExp is a TypeError, as with includes and endsWith. |
| position | number | no (0) | Treat the string as if it began here. startsWith("el", 1) tests the substring starting at index 1. |
Return value
boolean — True if the string begins with the search text — or begins with it at position, when one is given.
Common patterns
if (!url.startsWith('https://')) throw new Error('insecure');
const isInternal = PREFIXES.some(p => path.startsWith(p));
const rest = s.startsWith(p) ? s.slice(p.length) : s;
Examples
Pitfalls
'HTTPS://x'.startsWith('https://')
'HTTPS://x'.toLowerCase().startsWith('https://')
'https://evil.com/?x=bank.com'.startsWith('https://')
new URL(u).protocol === 'https:'
'abc'.startsWith(/a/)
/^a/.test('abc')
'hello'.startsWith('lo', 1)
'hello'.startsWith('lo', 3)
When to use
- Testing a protocol, scheme or known prefix
- Routing on a path prefix
- Detecting a marker at the beginning of a line
- Anywhere indexOf(x) === 0 appears
- The match may be anywhere → includes
- You are testing the end → endsWith
- You need a real pattern → an anchored RegExp with test
- Security decisions about URLs → the URL constructor
Notes
FAQ
startsWith for literal text. It needs no escaping, which matters when the prefix is a variable — a path or URL full of dots and slashes becomes a minefield inside a RegExp. Keep the anchored regex for genuine patterns.
s.startsWith(prefix); // safe new RegExp('^' + prefix).test(s); // needs escaping