Mastering JavaScript’s startsWith() Method

javascripts startswith

The startsWith() A method in JavaScript checks whether a string begins with a specific sequence of characters. It returns a boolean: true if it starts with the given substring, and false otherwise.

It’s case-sensitive, supports an optional position parameter, and is available in all modern JavaScript environments (since ES6/ES2015).

The startsWith() A method in JavaScript checks whether a string begins with a specific sequence of characters. It returns a boolean: true if it starts with the given substring, and false otherwise.

It’s case-sensitive, supports an optional position parameter, and is available in all modern JavaScript environments (since ES6/ES2015).

📘 Syntax

string.startsWith(searchString[, position])

Parameters:

  • searchString: The substring to check for at the start of the string.
  • position (optional): Index at which to begin the comparison. Defaults to 0. Negative or NaN values are treated as 0.

Return:

  • true if the string starts with searchString at the given position.
  • false otherwise.

🧠 Behavior Breakdown

🔤 Case-Sensitive

"JavaScript".startsWith("java"); // false

📍 Position Parameter

const str = "JavaScript is fun";
console.log(str.startsWith("Script", 4)); // true

Starts checking from index 4.


🔁 Edge Cases

// Empty string always returns true (if position is valid)
console.log("Hello".startsWith("")); // true
console.log("Hello".startsWith("", 5)); // true

// Position out of bounds
console.log("Hello".startsWith("H", 10)); // false
console.log("Hello".startsWith("", 10));  // true

// Negative or NaN position
console.log("Hello".startsWith("H", -5));  // true
console.log("Hello".startsWith("H", NaN)); // true

// Type coercion
console.log("123".startsWith(1)); // true (1 coerced to "1")
console.log("true".startsWith(true)); // true ("true" === "true")

✅ Real-World Examples

1. Basic Checks

const line = "To be, or not to be";
console.log(line.startsWith("To"));   // true
console.log(line.startsWith("to"));   // false (case-sensitive)

2. Using the Position Parameter

const text = "The quick brown fox";
console.log(text.startsWith("quick", 4)); // true

3. Filtering Arrays

const fruits = ["apple", "banana", "apricot"];
const filtered = fruits.filter(fruit => fruit.startsWith("a"));
console.log(filtered); // ["apple", "apricot"]

4. Validating URLs

const url = "https://example.com";

if (url.startsWith("https")) {
  console.log("Secure URL");
} else if (url.startsWith("http")) {
  console.log("Non-secure URL");
}

⚡ Performance Insights

  • Time Complexity: O(n), where n = searchString.length.
  • More performant and readable than str.slice(...) === ... or regex for prefix checks.
// Less readable and slightly slower
str.slice(0, prefix.length) === prefix;

// Overkill for simple checks
/^prefix/.test(str);

🌐 Environment & Compatibility

  • Supported in all modern browsers (Chrome, Firefox, Safari, Edge).
  • Fully supported in Node.js.
  • IE does not support it. Use a polyfill:
if (!String.prototype.startsWith) {
  String.prototype.startsWith = function(search, pos) {
    pos = pos || 0;
    return this.indexOf(search, pos) === pos;
  };
}

🛠 Common Use Cases

🔒 Input Validation

const phone = "+919876543210";
console.log(phone.startsWith("+91")); // true

🔍 Autocomplete Search

const suggestions = ["dog", "cat", "cow"];
const query = "c";
const matches = suggestions.filter(item => item.startsWith(query));
console.log(matches); // ["cat", "cow"]

📄 CSV/Log Parsing

const header = "ID,Name,Age";
if (header.startsWith("ID")) {
  console.log("Valid CSV header");
}

⚠️ Limitations & Gotchas

🔠 Case Sensitivity

const name = "Alice";
console.log(name.toLowerCase().startsWith("alice")); // true

❌ No Regex Support

const str = "123abc";
console.log(/^\d/.test(str)); // true

💡 Unicode Caution

const emoji = "😊hello";
console.log(emoji.startsWith("😊")); // true

🔁 Related String Methods

MethodPurpose
endsWith()Checks if a string ends with a substring
includes()Checks if substring exists anywhere
indexOf()Finds the index of substring

💡 Practical Tips

🧹 Trim User Input

const input = "  Hello";
console.log(input.trim().startsWith("Hello")); // true

🔗 Dynamic Prefix Match

const prefixes = ["http", "https", "ftp"];
const url = "https://example.com";
console.log(prefixes.some(p => url.startsWith(p))); // true

🧪 Debugging Tip

// Throws TypeError - startsWith called on null
console.log(null.startsWith("n")); // ❌

✅ Summary

The startsWith() method is:

  • Simple yet powerful.
  • Ideal for input validation, filtering, and prefix checks.
  • Supported across modern environments.
  • Readable and performant.

If you need case-insensitive or pattern-based checks, combine it with .toLowerCase() or use RegEx.


Optional Chaining in JavaScript

JavaScript Cheat Sheet

Understanding the hasOwnProperty() Method in JavaScript