Borislav Hadzhiev
Sat Oct 23 2021·2 min read
Photo by Josh Rocklage
The "Cannot read property 'replace' of undefined" error occurs when calling
the replace()
method on a variable that stores an undefined
value. To solve
the error, make sure to only call the replace
method on data types that
implement it, e.g. strings.
Here is an example of how the error occurs.
const str = undefined; // ⛔️️ Cannot read properties of undefined (reading 'replace') str.replace('test', 'replacement');
Because we called the replace()
method on an undefined value, we got the error
back.
Another common cause of the error is accessing an array at an index that doesn't
exist and calling the replace()
method.
const arr = []; // ⛔️️ Cannot read properties of undefined (reading 'replace') arr[0].replace('test', 'replacement'); // ✅ Use optional chaining (?.) instead const result = arr[0]?.replace('test', 'replacement');
To solve the error, you should initialize the value to an empty string and only
call the replace()
method on the correct data type.
const example = undefined; // ✅ Initialize to empty string const str = example || ''; // ✅ Using optional chaining (?.) const r1 = str?.replace('test', 'replacement'); console.log(r1); // 👉️ "" // ✅ Check if truthy if (str) { const r2 = str.replace('test', 'replacement'); } // ✅ Check if string if (typeof str === 'string') { const r3 = str.replace('test', 'replacement'); } // ✅ Provide fallback in place const r4 = (str || '').replace('test', 'replacement');
We used the logical OR (||) operator to provide a fallback value if the value to
the left is falsy (e.g. undefined
).
The next example shows how to use the optional chaining (?.) operator to short-circuit instead of throwing an error.
str
variable is equal to undefined
or null
, the optional chaining (?.) operator short-circuits returning undefined
.The next example checks if the value stored in the str
variable is truthy.
Since undefined
is a falsy value, it won't satisfy the condition.
The fourth example checks if the value has a type of string
before calling the
replace()
method.
The last example uses the logical OR (||) operator to provide a fallback in
place, right before calling the replace
method.
If you're getting the "Cannot read property 'replace' of undefined" error when working with DOM elements, make sure:
The "Cannot read property 'replace' of undefined" error occurs when calling the
replace()
method on an undefined
value.
To solve the error, provide a fallback for the value if it's equal to undefined and conditionally check that is stores the correct data type before calling the method.