Replace all

Currently, there are two ‘workarounds’ to replace all string occurrences in JavaScript, and the ‘new’ replaceAll method.

The workarounds

Using split and join:

  1. With the split method and a search value, divide the string into a list of substrings
  2. Create a new string, with the join method, by concatenating the above substrings with the replacement value in between

Example:

const newString = ‘foo bat bat’.split(‘bat’).join(‘bar’);

The first part: foo bat bat’.split(‘bat’) returns

Then, when we apply .join(‘bar’) we get a new string:

Using replace with regex + g (global flag)

The method replace() receives two parameters, a search value to look for and a replacement value.

  1. Create a regular expression (this is the search value) and append it the global flag g:
  2. Replace the occurrences with the replacement value.

Example:

const newString = ‘foo bat bat’.replace(/bat/g, ‘bar’);

const newString ='foo bat bat'.replace(RegExp('bat', 'g'), ‘bar');

The new way

The replaceAll() method

Right now, it is at stage 4 of the TC39 process.

String.prototype.replaceAll()

Example:

const newString = ‘foo bat bat’.replaceAll(‘bat’, ‘bar’);

Results

Looking for regex in *.js files (a subset from the NPM library)

Total number of replacements found: 386

Field Total Field Total
Backreferences in the search value 0, = 0% split() and join() methods 59, ~ 15.28%
Backreferences in the replacement value 47, ~ 12.18% replace() method and g flag 327, ~ 84.72%
Others ~ 87.82% replaceAll(): 0, = 0%

Attached files:

In markdown:

Pdf files:

Current project