One of the most used string prototypes in JavaScript is the replace function. It lets you change the first instance of a certain substring to whatever you want. If you need to change all instances of that substring, you could use another function called replaceAll.
That is, of course, if you are using NodeJS, in which case the function might not work. Let’s look at an example to see how it works.
let input = "00aa00bb00cc00dd"
let output = input.replaceAll('00', '');
console.log(output)
//OUTPUT
//TypeError: input.replaceAll is not a function
All major browsers work perfectly with the code above (except Internet Explorer). But if you try to use it in NodeJS versions 14 or lower, it tells you that replaceAll is not a function and yells at you.
So what’s up? “replaceAll” is not a string prototype that comes with NodeJS (below Node version 15). So, you get the error above. Let’s look at some other options down below.
How to replaceAll in Node JS
Since Node version 15, you can use the replaceAll method. If you are getting an error, it is likely because you are using an older version of Node.
One option is upgrading your Node environment. But in Node JS, you can also use the “replace” function with a regular expression instead of “replaceAll.” Let’s look at how to use it and how to add our own replaceAll function to use it over and over again.
Solution 1 – Use replace with regex
With the replace string prototype, we can change the first time a string appears in another string. But we can also give a regular expression to the replace function. Let’s look at a specific case.
let input = "00aa00bb00cc00dd"
let output = input.replace(/00/g,'')
console.log(output)
//OUTPUT
//aabbccdd
To finish the regex, we put the string we want to match between two forward slashes and then add the g flag. If you take out the g flag, the regular expression will once again only replace the first time it appears.
Solution 2 – Create your own replaceAll prototype
In the next example, we’ll give the String prototype a new method. This will let us use the replaceAll function on any string in our code.
String.prototype.replaceAll = function (target, payload) {
let regex = new RegExp(target, 'g')
return this.valueOf().replace(regex, payload)
};
let input = "00aa00bb00cc00dd"
let output = input.replaceAll('00', '');
console.log(output)
//OUTPUT
//aabbccdd
Inside our replaceAll prototype, we use a regular expression from Solution 1 with the standard replace function.
Solution 3 – Update to Node 15+
Depending on how your development and production environments are set up, updating your Node version to 15 or higher may be the easiest solution.
This could, of course, lead to problems in other parts of your code. Installing Node with a version manager like NVM is always a good idea (Node Version Manager).
So, you can easily install the latest version of Node, but if you need to, you can go back. It will also let you get a better idea of how the final production environment will look.