isotropic-2022
Share
Blog
Search
Menu

Cannot read property 'replace' of Undefined in JS

By Greg Murray
|
Last updated on April 27th, 2022
|

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:

const str = "hello world"; const modified = str.replace("world", "internet"); console.log(modified); // 'hello internet'

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').

The Problem

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:

let uninitializedString; console.log(uninitializedString.replace("", "")); // ❌ TypeError: Cannot read properties of undefined (reading 'replace') let arr = ["hello", "world"]; console.log(arr[0].replace("h", "y")); // 'yello' - ✔️ No error here! arr[0] = undefined; console.log(arr[0].replace("h", "y")); // ❌ TypeError: Cannot read properties of undefined (reading 'replace')

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?

The Solution

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:

let str = 0; let result; if (typeof str === "string") { result = str.replace("foo", "bar"); } else { result = "Variable is not a string"; } console.log(result); // 'Variable is not a string'

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:

let arr = [undefined, "world"]; let result = arr[0] ?? "hello"; console.log(result.replace("h", "y")); // 'yello'

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:

let arr = [undefined, "world"]; console.log((arr[0] ?? "hello").replace("h", "y")); // 'yello'

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 arr = [undefined, "world"]; console.log(arr[0]?.replace("h", "y")); // undefined

Let’s combine all of this together into a function you can use to safely perform .replace() on a string:

function safelyReplace(str, pattern, replacement) { // you could change this to whatever you need as your default value const defaultValue = ""; // first, make sure you are working with a string. if (typeof str !== "string") { return defaultValue; } // now, use optional chaining AND nullish coalescing to return the desired value or the default value. // if the string has a value, return the desired replace() result. // if the string is nullish, the left side of the ?? operator evaluates to undefined and defaultValue is used return str?.replace(pattern, replacement) ?? defaultValue; } console.log(safelyReplace("hello world", "world", "internet")); // ✔️ 'hello internet' console.log(safelyReplace(undefined, "world", "internet")); // ✔️ ''

Conclusion

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!

The Isotropic Codex is a collection of code snippets and education for WordPress, web and WooCommerce developers.
Subscribe & Share
If you liked this content, subscribe for our monthly roundup of WordPress news, website inspiration, exclusive deals and interesting articles.
Unsubscribe at any time. We do not spam and will never sell or share your email.
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Article By
Greg Murray
Contributors/Editors
notloggedin
I’m a passionate and driven web developer with an eye for design and appreciation for the human aspect of technology. I am experienced with building websites for small to medium businesses or large web applications for big businesses. Websites can be custom made using cutting edge technology and responsive design or created using the website builder of your choice.
We're looking for new authors. Explore Isotropic Jobs.
linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram