startsWith()

ES6+

Determines whether a string begins with the characters of a specified string.

Syntax

string.startsWith(searchString, position)

Parameters

searchString string

The characters to search for at the start

position number optional

Position to begin searching

Return Value

boolean

true if the string starts with the given characters

Examples

JavaScript
const str = 'Hello World';
console.log(str.startsWith('Hello'));
console.log(str.startsWith('World'));
Output:
// true false

📌 When to Use

Use startsWith() to check prefixes in strings, such as validating URL protocols, checking file types by mime type prefix, identifying command-line arguments, or verifying string format patterns.

⚠️ Common Mistakes

Forgetting that startsWith() is case-sensitive - "HTTP://example.com".startsWith("http") returns false.

Using indexOf() === 0 instead of startsWith() - startsWith() is more readable and expresses intent clearly.

Not using the position parameter when checking prefix after a known offset, resulting in unnecessary string manipulation.

✅ Best Practices

Use startsWith() for URL protocol validation: url.startsWith("https://") for secure connection checks.

Combine with toLowerCase() for case-insensitive prefix matching when protocol case may vary.

Use the position parameter to check prefixes at specific positions without creating substrings.

⚡ Performance Notes

startsWith() is highly optimized and only compares characters up to the length of the search string. It is more efficient than includes() when you only need to check the beginning of a string, as it does not need to scan the entire string.

🌍 Real World Example

URL and Protocol Validation

startsWith() is essential for validating URLs, checking file paths, parsing command strings, and routing based on path prefixes.

// Validate and normalize URL protocol
function ensureHttps(url) {
  if (url.startsWith('https://')) {
    return url;
  }
  if (url.startsWith('http://')) {
    return 'https://' + url.slice(7);
  }
  return 'https://' + url;
}

console.log(ensureHttps('http://example.com')); // 'https://example.com'
console.log(ensureHttps('example.com')); // 'https://example.com'

// Route handler based on path prefix
function routeRequest(path) {
  if (path.startsWith('/api/v2/')) {
    return { handler: 'apiV2', path: path.slice(8) };
  }
  if (path.startsWith('/api/')) {
    return { handler: 'apiV1', path: path.slice(5) };
  }
  if (path.startsWith('/static/')) {
    return { handler: 'static', path: path.slice(8) };
  }
  return { handler: 'page', path };
}

console.log(routeRequest('/api/v2/users'));
// { handler: 'apiV2', path: 'users' }

// Check MIME type category
function isImageMimeType(mimeType) {
  return mimeType.toLowerCase().startsWith('image/');
}

console.log(isImageMimeType('image/png')); // true
console.log(isImageMimeType('application/json')); // false

Related Methods