JavaScript String startsWith() Function: How It Works

Formulas & functions · Updated November 22, 2026

Yes. JavaScript provides the string method startsWith() to check whether a string begins with a specified sequence of characters. It returns true or false, and can optionally begin the check at a particular position.

What the startsWith() Method Does

startsWith() is a method on JavaScript strings, formally defined as String.prototype.startsWith(). It checks for an exact match at the beginning of a string, or at the beginning of a selected position within it. The method does not change the original string; it produces a Boolean result that you can use in a condition, assign to a variable, or return from another function.

A simple example is:

const language = 'JavaScript';
console.log(language.startsWith('Java')); // true
console.log(language.startsWith('script')); // false

The second result is false because the characters script appear later in the value, not at its start. The match is exact: capitalization, spaces, punctuation, and other characters all matter. The method is useful when the question is specifically “does this value begin with this text?” rather than “does this value contain this text anywhere?”

This method was introduced in ECMAScript 2015, also called ES6. It is supported by current major JavaScript engines and browsers. In unusual older environments, check for support before relying on it or use a compatible alternative.

Syntax and the Optional Position

The basic syntax is text.startsWith(searchString). The complete form is text.startsWith(searchString, position), where searchString is the sequence to look for and position is an optional starting index. If you leave out position, the method checks from index zero, the beginning of the string.

JavaScript string indexes count UTF-16 code units and start at zero. For ordinary English letters, this often looks like counting characters from zero, but some Unicode characters occupy more than one code unit. The position argument is converted to an integer and constrained to the range from zero through the string’s length. A negative position is treated as zero; a position beyond the end is treated as the end.

const message = 'Welcome, JavaScript';

console.log(message.startsWith('JavaScript')); // false
console.log(message.startsWith('JavaScript', 9)); // true

The second call checks at index 9, where JavaScript begins. This does not mean the method searches forward from that position. It checks only whether the requested sequence starts exactly there. To search anywhere after a position, use a search method such as indexOf() instead.

An empty search string is considered a match, so 'hello'.startsWith('') returns true. This follows from the fact that a zero-length sequence matches at the checked position, including the end of the string.

Practical Examples

Prefix checks are common when classifying text, choosing a display style, or deciding which handler should process a value. For example, a program might distinguish a command by its leading word:

const command = 'open settings';

if (command.startsWith('open ')) {
  console.log('This command opens something.');
}

Including the space in 'open ' helps avoid matching words such as 'opening'. The best prefix is the one that reflects the actual boundary in your data.

You can also combine the result with other conditions:

const fileName = 'report.csv';
const isReport = fileName.startsWith('report') && fileName.endsWith('.csv');

Here, startsWith() checks the leading text and endsWith() checks the suffix. Neither method confirms that a file exists or that its contents are valid; they only compare strings.

Because the result is Boolean, it can be used directly in a conditional or stored for later use:

const header = 'Content-Type: application/json';
const isContentTypeHeader = header.startsWith('Content-Type:');

For user-entered data, think carefully about whether leading spaces should count. A value such as ' admin' does not start with 'admin'. If whitespace should be ignored, trim it deliberately first: value.trim().startsWith('admin'). Trimming changes which text is checked, so it should match the requirements of your program rather than be added automatically.

Case Sensitivity, Types, and Unicode

startsWith() is case-sensitive. For example, 'JavaScript'.startsWith('java') returns false. If a particular task needs a case-insensitive comparison, convert both values to the same case before comparing:

const text = 'JavaScript';
const prefix = 'java';
const matches = text.toLowerCase().startsWith(prefix.toLowerCase()); // true

Case conversion is not a universal substitute for language-aware text comparison. Unicode has case-mapping details that can vary with language, and two visually identical strings can have different underlying character sequences. For user-facing, multilingual comparisons, consider whether normalization or locale-aware comparison is appropriate. For identifiers or protocol tokens, follow the case rules specified for that particular format.

The method expects a string receiver. A normal string primitive works directly. JavaScript will also convert a non-null receiver to a string when the method is called with it as this, such as with String.prototype.startsWith.call(123, '12'). Calling it on null or undefined throws a TypeError, because those values cannot be converted this way.

The search argument is converted to a string. This can surprise readers: passing a number searches for its string form, and omitting the argument is effectively like searching for the text 'undefined', not for an empty string. If the input might be missing, validate or provide a deliberate fallback rather than depending on implicit conversion.

The method compares string contents; it does not understand user-perceived characters as single visual units. Some emoji and other Unicode symbols are represented by multiple UTF-16 code units. A prefix that splits such a sequence may not behave the way a person looking at the rendered text expects. For exact text processing, be clear whether your data is defined in terms of code units, code points, or grapheme clusters.

startsWith() Compared With Other String Checks

Choose the method that matches the question your code needs to answer:

  • startsWith(prefix) checks for an exact match at the beginning or at the specified position.
  • includes(text) checks whether the text appears anywhere in the string.
  • indexOf(text) returns the first matching index, or -1 if there is no match.
  • endsWith(suffix) checks for an exact match at the end.
  • A regular expression can express more complex patterns, such as optional characters or several possible prefixes.

For example, 'report.csv'.startsWith('report') is true, while 'report.csv'.includes('.csv') is true because the suffix occurs somewhere in the text. If you use indexOf() to test a prefix, compare its result with zero: text.indexOf(prefix) === 0. Using only if (text.indexOf(prefix)) is a common mistake because index zero is falsy, while -1 is truthy.

For a straightforward literal prefix, startsWith() communicates intent more clearly than a regular expression. Typical regular expressions are not accepted as the search argument: 'abc'.startsWith(/a/) throws a TypeError. If the requirement is a pattern rather than a literal string, use a regular-expression operation such as test() instead.

Common Mistakes and Reliability

A frequent mistake is assuming the check ignores capitalization, whitespace, or punctuation. It does not. Another is treating it as a search-anywhere operation. The optional position changes where the exact check happens; it does not make the method scan through the remainder of the string.

Be cautious when using a prefix check as a security or validation boundary. A string beginning with a trusted-looking prefix is not necessarily a valid URL, path, account name, or command. For example, a URL can begin with https://trusted.example while its actual host is different. Parse URLs with the URL API and compare the parsed hostname or origin against an explicit allowlist. For file paths and other structured input, use the appropriate parser and canonicalization rules instead of relying on a raw text prefix.

Likewise, checking that a value starts with 'https://' only checks its textual scheme prefix. It does not establish that a connection is safe, that the host is trusted, or that the rest of the URL meets your application’s rules. Treat startsWith() as a string comparison tool, not as a complete validator.

If a value may not be a string, decide how the program should handle it before calling the method. For example, use a type check when only strings are acceptable. Converting every value with String(value) is possible, but may conceal unexpected input; for null, it produces the literal string 'null'. The right choice depends on whether conversion is intended or whether invalid data should be rejected.

Choosing a Clear and Compatible Approach

For modern JavaScript, use startsWith() when you need an exact prefix test. It is readable and directly expresses the operation. If supporting an old runtime is a real requirement, first identify the environments your application targets; broad support is better addressed through a project’s compatibility policy or build tooling than by adding a workaround without a defined need.

A basic feature check can determine whether the method exists:

const supportsStartsWith = typeof ''.startsWith === 'function';

When you only need a simple literal check in an older environment, text.indexOf(prefix) === 0 is a common alternative. Be sure the receiver and input are handled consistently, and remember that this alternative also performs an exact, case-sensitive string comparison. A regular expression is another option for pattern matching, but escaping user-provided text is necessary if that text is meant to be treated literally in a pattern.

In normal application code, there is no need to optimize between these approaches without evidence that a string check is a performance bottleneck. Prefer the clearest expression of the intended rule, and test edge cases that matter to your data: empty input, missing values, capitalization, spaces, and non-ASCII text.

Frequently Asked Questions

Does JavaScript have a string starts-with function?
Yes. Use the string method startsWith(), such as 'hello'.startsWith('he'), which returns true.

Is startsWith() case-sensitive?
Yes. A lowercase prefix does not match an uppercase character. Convert values to a consistent case only when that fits the comparison rules you need.

What does the second argument to startsWith() do?
It sets the position where the method checks for the prefix. It does not search forward from that position; the match must begin exactly there.

Can startsWith() check a regular expression?
No. A normal regular-expression object passed as the search argument causes a TypeError. Use a regular-expression method when you need pattern matching.

What does startsWith(”) return?
It returns true, because an empty sequence matches at the checked position. If an empty prefix should be considered invalid in your application, check for it separately.

Related

Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.

More in Formulas & functions

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.