String.prototype.replaceAll() not working

Javascript

Javascript Problem Overview


I need to replace all the string in a variable.

var a = "::::::";
a = a.replace(":", "hi");
console.log(a);

The above code replaces only the first string i.e..hi:::::: I used replaceAll but it's not working.

Javascript Solutions


Solution 1 - Javascript

Update: All recent versions of major browsers, as well as NodeJS 15+ now support replaceAll

Original:

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

Solution 2 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVishnu ChidView Question on Stackoverflow
Solution 1 - Javascriptuser166390View Answer on Stackoverflow
Solution 2 - JavascriptMitch SatchwellView Answer on Stackoverflow