TheAlgorithms/JavaScript · error · TypeError
Input must not contain numbers
Error message
Input must not contain numbers
What it means
Third guard in countLetters, fired by /\d/. After the type check and the special-character check, any decimal digit (0-9) throws TypeError. Combined with the previous guard this means countLetters only accepts pure ASCII letters [A-Za-z] (and underscores, which survive \W but produce an underscore key).
Source
Thrown at String/CountLetters.js:21
* @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
- Strip digits first: str.replace(/\d/g, '').
- Use a more permissive counter if you need digits included.
- Pre-validate the input is letters-only: /^[A-Za-z]+$/.test(str).
Example fix
// before
countLetters('abc123')
// after
countLetters('abc123'.replace(/\d/g, '')) Defensive patterns
Strategy: validation
Validate before calling
const clean = str.replace(/\d/g, '') countLetters(clean)
Type guard
const hasNoDigits = (s) => typeof s === 'string' && !/\d/.test(s)
Try / catch
try {
countLetters(str)
} catch (e) {
if (e instanceof TypeError && /numbers/i.test(e.message)) {
countLetters(str.replace(/\d/g, ''))
} else throw e
} Prevention
- Strip digits when counting letters only.
- Pre-validate with /^[A-Za-z]+$/.test(str).
- Remember underscores survive both guards and become a counted key.
When it happens
Trigger: Calling countLetters('abc123'), countLetters('a1b2'), countLetters('2024'). Any string containing a digit that already passed the special-char check.
Common situations: Alphanumeric identifiers (usernames, codes) passed where letters-only was assumed; alphanumeric reference numbers; forgetting the function is letters-only despite its name.
Related errors
- Input must not contain special characters
- Input should be a string
- Argument is not a valid HEX code!
- Invalid hex string.
- The given value is not a string
AI-assisted analysis of TheAlgorithms/JavaScript@5c39e87a9a (2026-08-13).
Data as JSON: /api/errors/7a2d91d664ca0880.
Report an issue: GitHub.