Strings in JavaScript have a wealth of helpful methods you can use to interact with or otherwise modify the contents of a string. One such method is 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')
.
JavaScript is a dynamically typed language so if there is any issue with the variable you are trying to use .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[0]
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:
With that out of the way, let’s explore some easy ways to prevent the error from ever happening. Using the string array example from before, you could provide a default value to use if the value of the string is undefined. Newer versions of JavaScript (ES2020+) can use the nullish coalescing operator ??
or, if you need to support older versions of JavaScript, you can use ||
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 undefined
.
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!