DEV Community

Cover image for JavaScript: Don't use replaceAll
Abdul Ghofur
Abdul Ghofur

Posted on

JavaScript: Don't use replaceAll

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,
})
Enter fullscreen mode Exit fullscreen mode

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

caniuse.com

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'
Enter fullscreen mode Exit fullscreen mode

Okay thanks.

Source

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more