How do you check if a string starts with a specific prefix in JavaScript? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

How do you check if a string starts with a specific prefix in JavaScript?

message-square
0

To check if a string starts with a specific prefix in JavaScript, validate that both the target value and prefix are strings (typeof targetStr === "string" and typeof prefix === "string"), call targetStr.startsWith(prefix, position) (with an optional starting index position when checking at an offset) inside a try / catch block—preferring .startsWith() over .indexOf(prefix) === 0 or regular expressions for clarity and speed—and use a Map when matching or classifying strings against multiple prefixes or rules so dynamic keys never collide with Object.prototype properties.


1. Checking a Prefix Safely with String.prototype.startsWith()

Validate targetStr and prefix with typeof checks and optional startIndex bounds, then run targetStr.startsWith(prefix, startIndex) inside try / catch:

// Check whether a string starts with a given prefix at an optional offset index
function hasStringPrefix(targetStr, prefix, startIndex = 0) {
  if (typeof targetStr !== "string") {
    throw new TypeError("Expected targetStr to be a string.");
  }
  if (typeof prefix !== "string") {
    throw new TypeError("Expected prefix to be a string.");
  }
  if (typeof startIndex !== "number" || !Number.isInteger(startIndex) || startIndex < 0) {
    throw new RangeError("Expected startIndex to be a non-negative integer.");
  }

  try {
    return targetStr.startsWith(prefix, startIndex);
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    throw new Error(`Failed checking prefix "${prefix}" on string: ${message}`);
  }
}

// Example usage:
// try {
//   console.log("HTTPS check:", hasStringPrefix("https://example.com", "https://")); // true
//   console.log("Offset check:", hasStringPrefix("api_v2_users", "v2", 4));          // true
//   console.log("Case-sensitive:", hasStringPrefix("Bearer token", "bearer"));         // false
// } catch (error) {
//   console.error(`${error.name}: ${error.message}`);
// }
  • .startsWith() is case-sensitive: Normalize case explicitly (such as .toLowerCase().startsWith(prefix.toLowerCase())) only when case-insensitive matching is desired.
  • An empty prefix ("") returns true for any string in .startsWith(""): Guard against empty prefixes explicitly if your domain requires a non-empty prefix.

2. Matching Multiple Prefixes and Categories with a Map

When classifying strings against multiple prefixes (such as URI schemes, log levels, or command namespaces), store prefix-to-category mappings in a Map so keys never collide with Object.prototype properties:

// Match a string against prefix rules stored in a Map and return the matched rule metadata
function matchPrefixFromMap(inputStr, prefixRulesMap) {
  if (typeof inputStr !== "string") {
    throw new TypeError("Expected inputStr to be a string.");
  }
  if (!(prefixRulesMap instanceof Map)) {
    throw new TypeError("Expected prefixRulesMap to be a Map instance.");
  }

  try {
    for (const [prefixKey, categoryLabel] of prefixRulesMap.entries()) {
      if (typeof prefixKey !== "string" || prefixKey.length === 0) {
        throw new TypeError("Expected every prefix key in prefixRulesMap to be a non-empty string.");
      }
      if (typeof categoryLabel !== "string" || categoryLabel.trim().length === 0) {
        throw new TypeError(`Expected category label for prefix "${prefixKey}" to be a non-empty string.`);
      }

      if (inputStr.startsWith(prefixKey)) {
        return new Map([
          ["matched", true],
          ["prefix", prefixKey],
          ["category", categoryLabel.trim()]
        ]);
      }
    }

    return new Map([
      ["matched", false],
      ["prefix", null],
      ["category", null]
    ]);
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    throw new Error(`Failed matching string against prefix Map: ${message}`);
  }
}

// Example usage:
// try {
//   const schemeRules = new Map([
//     ["https://", "secure-web"],
//     ["http://", "plain-web"],
//     ["mailto:", "email-link"]
//   ]);
//   const matchMap = matchPrefixFromMap("https://api.example.com/v1", schemeRules);
//   console.log("Matched category:", matchMap.get("category")); // "secure-web"
// } catch (error) {
//   console.error(`${error.name}: ${error.message}`);
// }
  • Use Map rather than {} for prefix tables: Avoids collisions with Object.prototype properties (constructor, toString, hasOwnProperty).
  • Order prefix entries intentionally when one prefix is a substring of another: Check more specific prefixes before shorter overlapping prefixes if ordering matters.

3. Regex Escaping, Leading Whitespace, and Type Caveats

Keep these prefix-checking details in mind in production code:

  • Prefer .startsWith() over building dynamic new RegExp("^" + ...): Dynamic regex strings easily break on special characters (., +, ?, *, [, (, $) unless escaped.
  • Watch leading whitespace and Unicode normalization: " https://..." does not start with "https://" unless trimmed or normalized first.
  • Avoid calling .startsWith() on non-strings (null, undefined, numbers, arrays): Always guard with typeof value === "string" first to avoid runtime TypeErrors.