skip to content
abdulghofurme

JavaScript: Don't use replaceAll

/ 2 min read

Instead of using replaceAll, it is better to use replace. But why? Doesn’t replace just replace the first character/sentence it finds?

The context of our discussion this time is replace & replaceAll which is a built-in function/method for String in JavaScript.

First, let’s see how to use it

const kalimat = "Kita akan membuka toko. Kita akan menjual kebab";

// replaceAll
const kalimatReplacedAll = kalimat.replaceAll("Kita", "Saya");

// replace
const kalimatReplaced = kalimat.replace("Kita", "Saya");

console.table({
	kalimat,
	kalimatReplacedAll,
	kalimatReplaced,
});

Above code will have output message like

(index)Value
kalimat‘Kita akan membuka toko. Kita akan menjual kebab’
kalimatReplacedAll‘Saya akan membuka toko. Saya akan menjual kebab’
kalimatReplaced‘Saya akan membuka toko. Kita akan menjual kebab’
  • replace & replaceAll don’t change the value, it returns the changed value.

    Therefore we have to accommodate the changes into a new variable.

  • replaceAll changes all findings, whereas replace changes only the first finding.

Problem

Then why? The problem is in compatibility

The problem that may occur is Runtime Error on some older devices/browsers.

Especially for friends who develop webview apps, this needs to be a concern.

Solution

Use replace. If you want to replace all findings, use Regular Expression with replace, as follows

const kalimatReplacedNew = kalimat.replace(/Kita/g, "Saya");
console.log(kalimatReplacedNew); // 'Saya akan membuka toko. Saya akan menjual kebab'

Okay thanks.

Source