143

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.

0

2 Answers 2

251

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

Sign up to request clarification or add additional context in comments.

11 Comments

@VishnuChid Because /:)/g is an invalid regular expression literal (it will result in a SyntaxError due to the "extra" closing parenthesis). Try /:\)/g instead. Please read the error messages and be precise about error messages - "not working" and "doesn't work" are very vague.
It's been many years since this answer was made, and replaceAll is now included in MDN documentation and the ECMA-262 (2021) spec, but replaceAll still isn't widely available in all browsers. Firefox is including it starting with version 77. Hopefully this update saves someone a few minutes of confusion.
Node JS does NOT support replaceAll !!!
As of node 15, node supports replaceAll.
|
85

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.

4 Comments

update 2021: String.prototype.replaceAll() is now a valid function in JS but has no support in Node yet. Example: ` let p = 'The dog ate my homework. Bad dog.'; p.replaceAll('dog', 'goat'); console.log(p); // 'The goat ate my homework. Bad goat.' `
Node 15 now supports replaceAll.
stackoverflow.com/questions/1144783/… clearly shows that there is too a 'replaceAll ' in JavaScript

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.