TheAlgorithms/JavaScript · error · TypeError

Input must not contain special characters

Error message

Input must not contain special characters

What it means

Second guard in countLetters, fired by the regex /\W/g. \W matches any character that is NOT [A-Za-z0-9_], so spaces, punctuation, hyphens, accented letters, and any non-ASCII letter all throw TypeError. Note: the underscore _ is a word character and does NOT throw here. The function therefore only accepts pure [A-Za-z0-9_] input (digits are caught by the next guard).

Source

Thrown at String/CountLetters.js:17

/**
 * @function countLetters
 * @description Given a string, count the number of each letter.
 * @param {String} str - The input string
 * @return {Object} - Object with letters and number of times
 * @example countLetters("hello") => {h: 1, e: 1, l: 2, o: 1}
 */

const countLetters = (str) => {
  const specialChars = /\W/g

  if (typeof str !== 'string') {
    throw new TypeError('Input should be a string')
  }

  if (specialChars.test(str)) {
    throw new TypeError('Input must not contain special characters')
  }

  if (/\d/.test(str)) {
    throw new TypeError('Input must not contain numbers')
  }

  const obj = {}
  for (let i = 0; i < str.toLowerCase().length; i++) {
    const char = str.toLowerCase().charAt(i)
    obj[char] = (obj[char] || 0) + 1
  }

  return obj
}

export { countLetters }

View on GitHub (pinned to 5c39e87a9a)

Solutions

  1. Strip non-letter characters first: str.replace(/[^A-Za-z]/g, '') before counting.
  2. If you actually want word/char counting on prose, use a different utility (e.g. CheckWordOccurrence).
  3. Pre-validate: if (/\W/.test(str)) sanitize or pick another function.

Example fix

// before
countLetters('hello world')

// after
countLetters('hello world'.replace(/[^A-Za-z]/g, ''))
Defensive patterns

Strategy: validation

Validate before calling

const clean = str.replace(/[^A-Za-z]/g, '')
countLetters(clean)

Type guard

const isLettersOnly = (s) => typeof s === 'string' && /^[A-Za-z]*$/.test(s)

Try / catch

try {
  countLetters(str)
} catch (e) {
  if (e instanceof TypeError && /special characters/i.test(e.message)) {
    countLetters(str.replace(/[^A-Za-z]/g, ''))
  } else throw e
}

Prevention

When it happens

Trigger: Calling countLetters('hello world') (space), countLetters('hi!'), countLetters('café') (é is non-word), countLetters('a-b'), countLetters('a,b').

Common situations: Passing free-text sentences to a function designed for single-letter token counting; expecting Unicode support when the regex is ASCII-only; forgetting that whitespace is a special character here.

Related errors


AI-assisted analysis of TheAlgorithms/JavaScript@5c39e87a9a (2026-08-13). Data as JSON: /api/errors/c13baf25f3645be9. Report an issue: GitHub.