JavaScript Replace All String

Mar 10, 2020

This following only replace first occurance of a string.

const str = "Replace all abc and abc."str.replace('abc', '0')     // "Replace all 0 and abc."

Replace all string occurances.

str.replace(/abc/g, '0')    // "Replace all 0 and 0."

or

const find = 'abc'const re = new RegExp(find, 'g')str.replace(re, '0')

Using function prototype

String.prototype.replaceAll = function(search, replacement) {    return this.replace(new RegExp(search, 'g'), replacement)}
str.replaceAll("abc", "0")

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.