Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.prototype.replaceAll() not working [duplicate]

Tags:

javascript

People also ask

Why replaceAll is not working in JS?

The "replaceAll" is not a function error occurs when we call the replaceAll() method on a value that is not of type string, or in a browser that doesn't support it. To solve the error, only call the replaceAll() method on strings in supported browsers.

Does replaceAll replace original string?

The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function to be called for each match. The original string is left unchanged.

What can I use instead of replaceAll in JavaScript?

To make the method replace() replace all occurrences of the pattern you have to enable the global flag on the regular expression: Append g after at the end of regular expression literal: /search/g. Or when using a regular expression constructor, add 'g' to the second argument: new RegExp('search', 'g')


There is no replaceAll in JavaScript: the error console was probably reporting an error.

Instead, use the /g ("match globally") modifier with a regular expression argument to replace:

const a = "::::::";
const replaced = a.replace(/:/g,"hi");
console.log(replaced);

The is covered in MDN: String.replace (and elsewhere).


There is no replaceAll function in JavaScript.

You can use a regex with a global identifier as shown in pst's answer:

a.replace(/:/g,"hi");

An alternative which some people prefer as it eliminates the need for regular expressions is to use JavaScript's split and join functions like so:

a.split(":").join("hi");

It is worth noting the second approach is however slower.