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

How do you check if a string contains a specific character in JavaScript?

message-square
0

To check if a string contains a specific character (or substring) in JavaScript, validate that both the target text and the search character/substring are string values, and call sourceString.includes(searchChar) (or use Unicode code-point / Set / regex checks when handling surrogate pairs/emojis, case-insensitive matching, or multiple candidate characters)—wrapping lookups in try / catch and avoiding indexOf(...) !== -1 when boolean readability and explicit validation are clearer.


1. Checking for a Character Safely with String.prototype.includes()

Validate both string arguments and use .includes() for exact, case-sensitive character or substring checks:

// Check whether a string contains a specific character (or substring) safely
function containsCharacter(sourceText, targetChar, { caseSensitive = true } = {}) {
  if (typeof sourceText !== "string") {
    throw new TypeError("Expected sourceText to be a string.");
  }
  if (typeof targetChar !== "string" || targetChar.length === 0) {
    throw new TypeError("Expected targetChar to be a non-empty string.");
  }
  if (typeof caseSensitive !== "boolean") {
    throw new TypeError("Expected caseSensitive to be a boolean.");
  }

  try {
    if (caseSensitive) {
      return sourceText.includes(targetChar);
    }

    return sourceText.toLowerCase().includes(targetChar.toLowerCase());
  } catch (error) {
    throw new Error(`Failed checking character presence: ${error.message}`);
  }
}

// Example usage:
// try {
//   console.log(containsCharacter("mustafabad", "a"));                       // true
//   console.log(containsCharacter("Mustafabad", "m", { caseSensitive: false })); // true
//   console.log(containsCharacter("hello-world", "@"));                      // false
// } catch (error) {
//   console.error(`${error.name}:${error.message}`);
// }
  • Validate typeof targetChar === "string" and targetChar.length > 0: Passing null, a number, or "" behaves unpredictably if unguarded ("".includes("") returns true natively).
  • Prefer .includes() over .indexOf() > -1: Communicates boolean intent directly without bit-level or -1 sentinel arithmetic.

2. Unicode-Aware Character Checks and Multi-Character Lookups via Set / Map

Strings containing emojis or supplementary Unicode code points (such as "🇵🇰" or "🚀") use UTF-16 surrogate pairs, so iterating with for...of (which yields full Unicode code points) and storing candidate characters in a Set or Map prevents false splits on surrogate halves:

// Check if a string contains any character from a Set of Unicode characters
function containsAnyCharacterFromSet(sourceText, allowedCharsSet) {
  if (typeof sourceText !== "string") {
    throw new TypeError("Expected sourceText to be a string.");
  }
  if (!(allowedCharsSet instanceof Set)) {
    throw new TypeError("Expected allowedCharsSet to be a Set instance.");
  }

  try {
    const matchedCountsMap = new Map();

    for (const ch of sourceText) {
      if (allowedCharsSet.has(ch)) {
        const currentCount = matchedCountsMap.get(ch) ?? 0;
        matchedCountsMap.set(ch, currentCount + 1);
      }
    }

    return {
      found: matchedCountsMap.size > 0,
      matches: matchedCountsMap
    };
  } catch (error) {
    throw new Error(`Failed scanning characters with Set: ${error.message}`); } }  // Example usage: // try { //   const delimiters = new Set([",", ";", "\vert{}", "\n"]); //   const result = containsAnyCharacterFromSet("a,b\vert{}c", delimiters); //   console.log("Found:", result.found, "Matches:", result.matches); // true, Map { ',' => 1, '\vert{}' => 1 } // } catch (error) { //   console.error(`${error.name}: ${error.message}`); // }  - **Use `for...of` instead of index indexing (`str[i]`) for non-BMP characters:** `str[i]` reads a single UTF-16 code unit, whereas `for...of` iterates full Unicode code points. - **Store candidate characters in a `Set`:** Provides clean membership checks and pairs naturally with a `Map` for match counts.  ---  ## 3. Case Folding, Regex Escaping, and Edge Cases  Keep these string-matching pitfalls in mind when checking for characters in production code:  - **Escape special characters if building a `RegExp` dynamically:** Characters like `.`, `*`, `+`, `?`, `[`, `]`, `(`, `)`, `{`, `}`, `^`, `$`, `|`, and `\` have special regex meaning—prefer `.includes()` or `Set.has()` unless pattern matching is required.
  • Beware locale-specific case rules (such as dotted/dotless i in "tr"): Simple .toLowerCase() works for standard ASCII/Latin checks, while locale-sensitive text may need explicit locale handling.
  • Check typeof sourceText === "string" before calling string methods: Passing null, undefined, numbers, or objects throws a TypeError if not validated upfront.