Cannot read property ‘replace’ of Undefined in JS
String.prototype.replace() which lets you create a new string by replacing the first occurrence of a pattern (regular expression or string) with a given string value. For example:
This can be very useful but sometimes runtime errors may come up while using this method such as
TypeError: Cannot read properties of undefined (reading 'replace').
.replace() on, you could run into an error at run time. As the error above suggests, the problem comes from the fact that the variable you’ve used has a value of undefined. This could be because the variable was never given a string value or the value has unexpectedly changed to undefined over the course of the script’s execution. Let’s illustrate what that might look like:
In the above example, the first string was not initialized so the error showed up. The second string worked fine at first because there was a value at
arr but once that value became undefined you see the error again. So how can you avoid this?
To be completely safe, the first thing you can do is just make sure the string you are trying to use
replace() on is actually a string. This does not necessarily prevent the error in all cases but can at least prevent some possible issues using this method:
|| in this instance:
Basically the way this works is if the value of the left side of the
?? operator is null or undefined, the right side will be used. In this case, that means “hello” is used and no errors are encountered. You can accomplish this inline if that is more your style:
If you simply want a way to safely use
.replace() without run time errors but do not really care about having a default value, use optional chaining. Keep in mind that this will make the expression evaluate to
Let’s combine all of this together into a function you can use to safely perform
.replace() on a string:
There you have it, hopefully that gives you some understanding behind the error you have received and, at the very least, a few different options to use to avoid it in the future. Let us know if you have a different way to solve this or if there is something else you’d like to see us write about!