How to Fix replaceAll is not a function in Node.js

Tek Loon
2 min readJun 13, 2021

--

Photo by Mika Baumeister on Unsplash

In this post, I will be sharing the root cause of replaceAll is not a function error and what is the workaround solution for this problem.

The above code is straightforward and it should be working as usual. However, if you’re running the code with Node version below 15.0, you would encounter the below error.

TypeError: title.replaceAll is not a function

This is because replaceAll function is only available starting from Node version 15.

Solutions

There are 2 solutions to the above problem.

  1. Upgrade your Node.js version to 15.0 and above
  2. Using replace function with regex

Solution 1 might be the easiest solution, but it’s not really practical in real-life situations. Upgrading the Node.js version in production always needs to consider the library dependencies and it takes time to ensure your application work as usual.

So, we will focus on solution 2 instead which is a more practical approach. We can simply change replaceAll function to replace . Refer to the code snippet below.

The regex / /g we used here is matching empty space with the global flag. Basically, we're telling the replace function that we're replacing all occurrences - in short, replacing all empty space exists in the sentence.

However, if you choose to write the regex without global flag — / /, it will only replace the 1st matching empty space and this is not the desired output.

Conclusion

From this post, we know that function replaceAll only available in Node version 15 and above. However, we could also use replace function and regex to help us achieve the desired output of replaceAll without upgrading the Node.js version.

Please let me know if you find this post is helpful. 👏👏

--

--

Tek Loon
Tek Loon

Written by Tek Loon

Coder and Writer. If you enjoy my stories— support me by https://www.buymeacoffee.com/tekloon so I can keep writing articles for the community.

No responses yet