Skip to main content

Command Palette

Search for a command to run...

replaceAll in JavaScript

Updated
β€’2 min read
replaceAll in JavaScript
S

I am Senior Frontend Engineer and post daily tips about Web Dev

My goal is to encourage more people to get into tech.

String.prototype.replaceAll() replaces all occurrence of a string with another string value.

Syntax:

const newStr = str.replaceAll(regexp|substr, newSubstr|function)

There are few ways to replace all occurrence of a string:

  1. RegEx
  2. split and join
  3. replaceAll

1. RegEx πŸ™…β€β™€οΈ

const info = "Hi All, suprabha's account is @suprabha";
const newInfo = info.replace(/suprabha/g, "suprabha supi");
console.log(newInfo); // "Hi All, suprabhasupi's account is @suprabhasupi"

2. split and join δ·– ⊞

Using split and join, replace all the occurrence of a string.

const info = "Hi All, suprabha's account is @suprabha";
const newInfo = info.split('suprabha').join('suprabhasupi');
console.log(newInfo); // "Hi All, suprabhasupi's account is @suprabhasupi"

Till now, you were able to do full replacement with above two approaches. Now we have replaceAll which helps us to do the same.

3. replaceAll πŸš€

The Mathias bynens proposal solves these problems and gives a very easy way to do substring replacement using replaceAll() which replaces all instances of a substring in a string with another string value without using a global regexp.

const info = "Hi All, suprabha's account is @suprabha";
const newInfo = info.replaceAll('suprabha','suprabhasupi');
console.log(newInfo); // "Hi All, suprabhasupi's account is @suprabhasupi"

You can also pass RegEx to first parameter in replaceAll.

const info = "Hi All, suprabha's account is @suprabha";
const regex = /suprabha/ig;
const newInfo = info.replaceAll(regex,'suprabhasupi');
console.log(newInfo); // "Hi All, suprabhasupi's account is @suprabhasupi"

Note: 🧨

When using a regexp you have to set the global ("g") flag; otherwise, it will throw a TypeError: "replaceAll must be called with a global RegExp".

You also have replace() method, which replaces only the first occurrence if the input pattern is a string.

const info = "Hi All, suprabha's account is @suprabha";
const newInfo = info.replace("suprabha", "suprabhasupi");
console.log(newInfo); // "Hi All, suprabhasupi's account is @suprabha"

Reference 🧐

🌟 Twitter | πŸ‘©πŸ»β€πŸ’» suprabha.me | 🌟 Instagram

J

Thanks, I like the manner of concise writing and shortness in your expanation. I would like to sync your article to the Programiz blog and add as a JavaScript String Replace() guide explained by custom examples.

How to do my assignment in Java https://essaydune.com/do-my-assignment/

1
S

Hey Jason,

Yes sure. You can definitely sync this article. ☺️