ECMAScript 2021(ES12) introduces replaceAll method and numeric separators


ECMAScript 2021(ES12) is the latest JavaScript version that introduced multiple new features to the JavaScript language.

In this blog, we will cover replaceAll() method and numeric separators that was a part of ECMAScript 2021 additions.

String.prototype.replaceAll()

String.prototype.replaceAll() method replaces all instances of a substring in a string with a new string value.

Syntax

String.prototype.replaceAll(subString, newSubstring)

Parameters

subString: Input string that is to be replaced by a new value. It can be a string or a regular expression.

newSubstring: The string that replaces the substring argument

Return value

The original string is left unchanged and a new string is returned.

Before

Before ECMAScript 2021 one of the most common ways of doing this was to use a global regexp.

const pangram = "the quick brown fox jumps over the lazy dog";

const pangramReplaced = pangram.replace(/the/g, 'a');
// a quick brown fox jumps over a lazy dog

Now, this approach works fine but using regular expression is not easy, they are also not easy to read and error-prone.

After

Starting with ECMAScript 2021 we have a straightforward way to solve this problem.

const pangram = "the quick brown fox jumps over the lazy dog";

pangram.replaceAll('the', 'a');
// a quick brown fox jumps over a lazy dog

Now let us take a look at the numeric separator.

Numeric Separator

Numeric separator(_) allows users to make their numeric literals more readable by creating a the visual separation between groups of digits.

Before

const num = 100000000000;
// Good luck counting the zeroes

After

const num = 1_000_000_000_00;

Position of Separator

A numeric separator can appear anywhere inside the number.

These are some of the valid usages of numeric separators

1_000_000_000_00
100_00_00
1_2_3_4
12345_77

However, numeric separator is not allowed at the starting or at the end of the number.

_1000 // Invalid, if a number starts with `_` it's treated as a variable name
1000_ // Invalid

The numeric separator can be applied to number, float, binary, hex, octal and bigint literal types.

Following are some of the valid examples for different literal types.

const num = 1_000_000_000_000;
const floatNumber = 3.144_444;
const binaryNumber= 0b1110_0001_1010_0101;
const hexaNumber = 0xf_f;
const octalNumber = 0o45_23_12;
const bigIntNumber = 9_453_342_636_874_745_146n;