JavaScript startsWith() Method Explained Simply

startsWith() is a useful string method for checking if a string begins with specific characters. In this post, we’ll explore how it works, when to use it, and how it compares to other string methods.

Introduction to startsWith()

Definition and Purpose

The startsWith() method checks whether a string begins with the characters of a specified string. It returns true if the string starts with the specified characters, and false otherwise.

const message: string = "Hello, world!";
console.log(message.startsWith("Hello")); // true
console.log(message.startsWith("world")); // false

This method is essential for string validation, checking file extensions, validating URLs, and many other common programming tasks.

Syntax Overview

The basic syntax is:

string.startsWith(searchString: string, position?: number): boolean
  • searchString: The characters to search for at the beginning of the string
  • position (optional): The position to start searching from (defaults to 0)

Core Functionality

How startsWith() Works

The method performs a simple character-by-character comparison starting from the beginning of the string (or from the specified position). It’s case-sensitive and stops as soon as it finds a mismatch.

const text: string = "JavaScript is awesome";
console.log(text.startsWith("Java"));     // true
console.log(text.startsWith("java"));     // false (case-sensitive)
console.log(text.startsWith("Script"));   // false (not at start)

Return Values

The method returns a boolean:

  • true: The string starts with the specified characters
  • false: The string doesn’t start with the specified characters

Edge cases:

const str: string = "Hello";
console.log(str.startsWith(""));          // true (empty string)
console.log(str.startsWith("Hello"));     // true (exact match)
console.log(str.startsWith("Hello!"));    // false (longer than original)

Parameters in Depth

searchString Parameter

The searchString parameter is what you’re looking for at the beginning of the string:

const filename: string = "document.pdf";
console.log(filename.startsWith("doc"));      // true
console.log(filename.startsWith("document")); // true
console.log(filename.startsWith("pdf"));      // false

Limitations:

  • Must be a string (other types are converted)
  • Case-sensitive matching
  • Cannot use regex patterns
const text: string = "Hello123";
console.log(text.startsWith(123));        // false (converted to "123")
console.log(text.startsWith("hello"));    // false (case-sensitive)

position Parameter

The position parameter lets you start the search from a specific index:

const text: string = "Hello world, hello universe";
console.log(text.startsWith("world", 6));     // true (starts at index 6)
console.log(text.startsWith("hello", 13));   // true (starts at index 13)
console.log(text.startsWith("Hello", 13));   // false (case-sensitive)

Use Cases and Examples

Basic String Validation

Checking file extensions:

function isImageFile(filename: string): boolean {
    return filename.startsWith("image.") || 
           filename.startsWith("photo.") || 
           filename.startsWith("img.");
}

console.log(isImageFile("image.jpg"));    // true
console.log(isImageFile("document.pdf")); // false

Validating URL protocols:

function isValidUrl(url: string): boolean {
    return url.startsWith("http://") || 
           url.startsWith("https://") || 
           url.startsWith("ftp://");
}

console.log(isValidUrl("https://example.com")); // true
console.log(isValidUrl("file:///path"));        // false

Advanced Implementations

Text analysis:

function analyzeText(text: string): string {
    if (text.startsWith("ERROR:")) {
        return "This is an error message";
    } else if (text.startsWith("WARNING:")) {
        return "This is a warning message";
    } else if (text.startsWith("INFO:")) {
        return "This is an info message";
    }
    return "Unknown message type";
}

console.log(analyzeText("ERROR: Something went wrong")); // "This is an error message"

Combining with other methods:

function processCommand(input: string): string {
    const trimmed: string = input.trim();
    
    if (trimmed.startsWith("/help")) {
        return "Showing help information...";
    } else if (trimmed.startsWith("/search")) {
        const query: string = trimmed.substring(8); // Remove "/search "
        return `Searching for: ${query}`;
    } else if (trimmed.startsWith("/quit")) {
        return "Goodbye!";
    }
    return "Unknown command";
}

Performance Considerations

Efficiency Compared to Alternatives

startsWith() is generally faster than alternatives:

const text: string = "Hello world";
const searchTerm: string = "Hello";

// Method 1: startsWith() - Fastest
console.log(text.startsWith(searchTerm));

// Method 2: indexOf() - Slower
console.log(text.indexOf(searchTerm) === 0);

// Method 3: RegExp - Slowest
console.log(/^Hello/.test(text));

Performance comparison:

  • startsWith(): O(n) where n is searchString length
  • indexOf() === 0: O(n) but with additional comparison
  • RegExp: O(n) but with regex compilation overhead

Avoid unnecessary conversions:

// Good - direct string comparison
if (text.startsWith("Hello")) { }

// Avoid - unnecessary conversion
if (text.startsWith(String("Hello"))) { }

Browser Compatibility and Polyfills

Support Across Browsers

startsWith() is well-supported in modern browsers:

  • Chrome 41+ (2015)
  • Firefox 17+ (2013)
  • Safari 9+ (2015)
  • Edge 12+ (2015)

Implementing Polyfills

For older browsers, you can create a polyfill:

if (!String.prototype.startsWith) {
    String.prototype.startsWith = function(searchString: string, position?: number): boolean {
        position = position || 0;
        return this.indexOf(searchString, position) === position;
    };
}

Common Pitfalls and Troubleshooting

Case Sensitivity Issues

startsWith() is case-sensitive, which can cause unexpected behavior:

const filename: string = "Document.pdf";
console.log(filename.startsWith("doc")); // false!

// Solution: Convert to lowercase first
console.log(filename.toLowerCase().startsWith("doc")); // true

Creating a case-insensitive version:

function startsWithIgnoreCase(str: string, searchString: string, position?: number): boolean {
    return str.toLowerCase().startsWith(searchString.toLowerCase(), position);
}

console.log(startsWithIgnoreCase("Hello", "hello")); // true

Advanced Topics

startsWith() in Regular Expressions

While startsWith() can’t use regex directly, you can combine them:

function startsWithPattern(str: string, pattern: string): boolean {
    const regex: RegExp = new RegExp(`^${pattern}`);
    return regex.test(str);
}

console.log(startsWithPattern("Hello123", "Hello\\d+")); // true
console.log(startsWithPattern("Hello", "Hello\\d+"));    // false

Functional Programming with startsWith()

Currying example:

const startsWith = (searchString: string) => (str: string): boolean => str.startsWith(searchString);
const startsWithHello: (str: string) => boolean = startsWith("Hello");

console.log(startsWithHello("Hello world")); // true
console.log(startsWithHello("Goodbye"));     // false

Conclusion and Best Practices

When to Use startsWith()

Use startsWith() when:

  • Checking if a string begins with specific characters
  • Validating file types, URLs, or commands
  • Simple prefix matching (case-sensitive)
  • Performance is important

Consider alternatives when:

  • You need case-insensitive matching (use toLowerCase() first)
  • You need regex pattern matching
  • You’re searching anywhere in the string (use includes())

If this article was helpful, tweet it!