How to replace all occurrences of a string in JavaScript?

September 29, 2022 No comments replace occurrences string js tips javascript

Introduction

Sometimes, we'll like to replace all occurrences of a string in JavaScript.

In this article, we'll present how to do that.

How to replace all occurrences of a string in JavaScript

To replace all occurrences of a string in JS we can use the replaceAll() function introduced in ECMAScript 2021 specification.

const s = 'This abc is a abc sample test abc';
console.log(s.replaceAll('abc', '').replaceAll('  ', ' ')); // This is a sample test

If your browser does not support the replaceAll() method you can use regular expression-based replacement:

String.prototype.replaceAll = function(search, replacement) {
    var target = this;
    return target.replace(new RegExp(search, 'g'), replacement);
};

Conclusion

To replace all occurrences of a string in JS we can use replaceAll() method or string.replace() with regexp function.

{{ message }}

{{ 'Comments are closed.' | trans }}