Skip to content

TypeError: x.replace is not a function

Quick summary

You called .replace (or .trim, .split) on a number, array, or object — those methods only exist on strings.

Why this happens

  • A variable that should be a string is actually a number or array

  • JSON.parse returned a number where a string was expected

  • A function parameter was not validated before calling a string method on it

Minimal example

✗ Broken code
const id = 12345;
console.log(id.replace('1', 'x')); // TypeError: id.replace is not a function
✓ Fixed code
const id = 12345;
console.log(String(id).replace('1', 'x')); // 'x2345'

id is a number, which has no .replace method. Converting with String(id) first lets you call the string method safely.

How to diagnose

  • Read the TypeError: 'x.replace is not a function'

  • Log typeof x and the actual value before the call

  • Trace where the value came from to find the type mismatch

How to fix

  • Convert the value to a string with String(x) before calling the method

  • Fix the source so it produces a string as expected

  • Add a type check and branch before calling string-only methods

How to prevent

  • Validate types at function boundaries

  • Use TypeScript to catch type mismatches at compile time

Related Resources

Related Glossary

Related Lessons

← Back to language