Sling Academy
Home/JavaScript/JavaScript String replaceAll() method (with examples)

JavaScript String replaceAll() method (with examples)

Last updated: February 14, 2024

Overview

The replaceAll() method in JavaScript is a powerful tool for string manipulation, allowing developers to replace all occurrences of a substring within a given string with another substring. This method is relatively new, having been introduced in ECMAScript 2021 (ES12). Prior to its introduction, achieving the same result required either complex regular expressions or looping constructs.

What is replaceAll() Used For?

The primary use of the replaceAll() method is to find all instances of a specific substring in a string and replace them with a different substring. This is especially useful in text processing, data cleaning, or any scenario where consistent replacement throughout a string is required.

Syntax, Parameters, and Return Value

Syntax:

str.replaceAll(searchValue, newValue)

Parameters:

  • searchValue – The substring to be replaced. Can be a string or a global RegExp.
  • newValue – The string to replace each match. Can also be a function that returns the replacement string.

Return Value:

A new string, with all matches of the searchValue replaced by newValue.

Code Examples

Basic Replacement

This example demonstrates replacing all instances of ‘dog’ with ‘cat’ in a sentence.

const sentence = 'The quick brown dog jumps over the lazy dog.';
const newSentence = sentence.replaceAll('dog', 'cat');
console.log(newSentence);
// Output: The quick brown cat jumps over the lazy cat.

Using a Function as newValue

This example shows how to dynamically generate the replacement string for each match using a function.

const message = 'I owe you 30 dollars and 45 dollars.';
const updatedMessage = message.replaceAll(/\d+/g, (match) => `${parseInt(match, 10) * 1.1}`);
console.log(updatedMessage);
// Output: I owe you 33 dollars and 49.5 dollars.

Conclusion

The replaceAll() method is a significant addition to the JavaScript language, simplifying the task of replacing substrings throughout a string. Its introduction in ECMAScript 2021 has filled a notable gap in the language’s string manipulation capabilities, making certain tasks more straightforward and cleaner to implement. As we’ve seen through examples, whether you’re dealing with simple string replacements or need to use a function for a dynamic replacement, replaceAll() elegantly addresses these needs.

Next Article: Using logical nullish assignment in JavaScript (with examples)

Previous Article: Nullish Coalescing in JavaScript: A Developer’s Guide

Series: JavaScript Basics

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration