How to Fix the "Cannot Read Property 'replace' of Undefined" Error in JavaScript

Are you experiencing the "cannot read property 'replace' of undefined" error in JavaScript? This error occurs when you attempt to call the replace()
method on a variable that has a value of undefined
.
const str = undefined;
// TypeError: Cannot read properties of undefined (reading 'replace')
const newStr = str.replace('old', 'new');
console.log(newStr);
To fix the "cannot read property 'replace' of undefined" error, perform an undefined
check on the variable before calling the replace()
method on it. There are various ways to do this, and we'll cover 4 of them in this article.
11 Amazing New Features in ES13

1. Use an if Statement
We can use an if
statement to check if the variable is truthy before calling the replace()
method:
const str = undefined;
let result = undefined;
// Check if truthy
if (str) {
result = str.replace('old', 'new');
}
console.log(result); // undefined
2. Use Optional Chaining
We can use the optional chaining operator (?.
) to return undefined
and prevent the method call if the variable is nullish (null
or undefined
):
const str = undefined;
// Optional chaining
const result = str?.replace('old', 'new');
console.log(result); // undefined
3. Call replace() on a Fallback Value
We can use the nullish coalescing operator (??
) to provide a fallback value to call replace()
on.
const str = undefined;
const result = (str ?? 'old str').replace('old', 'new');
console.log(result); // 'new str'
The null coalescing operator (??
) returns the value to its left if it is not null
or undefined
. If it is, then ??
returns the value to its right.
console.log(5 ?? 10); // 5
console.log(undefined ?? 10); // 10
4. Use a Fallback Result Instead of Calling replace()
We can combine the optional chaining operator (?.
) and the nullish coalescing operator (??
) to provide a fallback value to use as the result, instead of performing the replacement.
const str = undefined;
const result = str?.replace('old', 'new') ?? 'no matches';
console.log(result); // 'no matches'
11 Amazing New Features in ES13

See also
- How to Fix the "Cannot read property 'toString' of undefined" Error in JavaScript
- How to easily fix the "Cannot read property 'classList' of null" error in JavaScript
- How to Fix the "Cannot read property of undefined" Error in JavaScript
- How to Fix the "Cannot read Property 'push' of Undefined Error in JavaScript
- How to quickly fix the "Cannot read property 'then' of undefined" error in JavaScript
- How to Fix the "Cannot access before initialization" Reference Error in JavaScript