6) Advanced Arrays, Strings and Functions Lesson

How to Replace Strings in JavaScript

19 min to complete · By Ian Currie

Replacing strings within text is an essential tool for any JavaScript developer. In this lesson, you will dive into various methods of string replacement in JavaScript. From simple string replacements to the powerful capabilities of regular expressions, you'll learn how to substitute parts of a string seamlessly.

By the end of this lesson, you'll be well-equipped to handle a wide range of string replacement tasks. Whether it's updating user-generated content, modifying data for display, or even complex pattern replacements, the techniques you learn here will be a valuable addition to your programming toolkit.

If you're more interested in finding strings rather than replacing them, check out the previous lesson in this course which covers that in detail. Nevertheless, many of the concepts and techniques are shared between both lessons.

Replacing Strings in JavaScript

There are two main string methods dedicated to replacing strings in JavaScript: .replace() and .replaceAll(). Each method can be used with standard strings as arguments but they can also leverage the power of regular expressions. They can even support callback functions to perform complex string replacements.

In this lesson, you'll go from basic string replacement to advanced techniques. With that, in the next section, you'll be doing a straightforward string replacement with .replace().

Basic String Replacement with .replace()

The .replace() method is the most common way to replace strings in JavaScript. It takes two arguments: the string to replace (the "pattern") and the string to replace it with (the "replacement"). For example, you can replace the word "lorem" with "ipsum" in the following way:

let greeting = "Hello, world!";
greeting.replace("world", "internet"); // Hello, internet!

// You can also call string methods directly on the string literal:
"Hello, world!".replace("world", "internet"); // Hello, internet!

This examples shows replacement at it's most basic. Yet there are many situations in which you may want something a bit more powerful. For example, what if you want to replace all instances of a string?

Replacing All Instances of a String with .replaceAll()

The .replaceAll() method is similar to .replace() but it replaces all instances of the string given as the first argument:

"Hello, world! The world is beautiful.".replaceAll("world", "internet");
// Hello, internet! The internet is beautiful.

Sometimes you want to make a bunch of replacements in a text. If so, then a useful pattern is chaining the .replaceAll() method:

let text = `Hello, world! The world is beautiful.
  We must protect the beautiful world.
  We must protect the beautiful world!
  `;

text
  .replaceAll("world", "internet")
  .replaceAll("the", "our")
  .replaceAll("The", "Our")
  .replaceAll("beautiful", "wonderful")
  .replaceAll("protect", "save");

/*
Hello, internet! Our internet is wonderful.
We must save the wonderful internet.
We must save the wonderful internet!
*/

Now you've replaced multiple strings in a single text. Now it's time to leverage the power of regular expressions.

Leveraging Regex with .replace() and .replaceAll()

Sometimes the replacements you need to make are more complex than simple string replacements. For example, you may want to replace all instances of a word except when it's capitalized. Or you may want to replace all instances of a word only when it's capitalized. Or all instances of e-mails. When you need these types of replacements, reach for regular expressions.

If you want to know more about how to initialize a RegExp object in JavaScript, check out the previous lesson in this course. For now, let's look at some examples of how to use regular expressions with .replace() and .replaceAll().

Find and Replace Strings With Regex

The basic way that the replace method works is very similar to match. You have a regex expression to find the string that you want to match, but you also define what string you want to replace that match with. For example:

let text = "Java, java, JAVA, jAVA";
text.replace(/java/i, "JavaScript");
// "JavaScript, java, JAVA, jAVA"

In this example, you instantiated the RegExp object /java/i to find the string "java" in the text. The i flag makes the search case-insensitive. Then you defined the string "JavaScript" as the replacement. The result is that the first instance of "java" is replaced with "JavaScript".

If you need to replace all instances of a string, you can use the .replaceAll() method:

let text = "Java, java, JAVA, jAVA";

text.replaceAll(/java/gi, "JavaScript");
// "JavaScript, JavaScript, JavaScript, JavaScript"

text.replace(/java/gi, "JavaScript");
// "JavaScript, JavaScript, JavaScript, JavaScript"

In this example, you used the .replaceAll() method to replace all the instances of "java" with "JavaScript". You also used the gi flags to make the search case-insensitive and global.

Illustration of a lighthouse

The g flag is necessary when using the .replaceAll() method with a RegExp pattern as an argument. If you don't include it, the method will throw a TypeError saying that you're using a regular expression without the g flag.

Interestingly, if you include the g flag on the regular .replace() method you'll get the same behavior as .replaceAll():

text.replace(/java/gi, "JavaScript");
// "JavaScript, JavaScript, JavaScript, JavaScript"

It may seem confusing to have both ways. Why use .replaceAll() if you can do the same thing with .replace()? The answer is that .replaceAll() is more explicit and readable. It makes it harder for you as a developer to make a mistake. This is sometimes called "fail fast" programming. It's better to fail fast and get an error than to fail silently and have a bug in your code.

Having .replaceAll() also means that you can do replace and replace all operations without having to use regex at all, as shown in the introductory examples in this lesson where you use a normal string as an argument.

It's also worth noting that .replace() existed before .replaceAll(). The latter was added in ES2021. So if you were working before .replaceAll() existed, then you would have had to use .replace() with the g flag to replace all instances of a string.

Find and Replace Strings With Regex and Capture Groups

You can also use capture groups to replace strings with regular expressions. Capture groups are useful when you want to replace a string with a modified version of itself. For example, you may want to redact a list of emails, replacing the email address with the domain name only.

To use capture groups, you need to wrap the part of the string you want to capture in parentheses. You can use this with both the .replace() or .replaceAll() methods. For example, you can capture the first letter of a word with the following regular expression:

let text =
  "[email protected], [email protected], [email protected]";

text.replaceAll(/\S+@(\S+\.\S+)/gi, "$1");
// lemon-aid.io, wooflogistics.com, eggnogemporium.net

// Also works with .replace():
text.replace(/\S+@(\S+\.\S+)/i, "$1");
// lemon-aid.io, [email protected], [email protected]

In this example, you used the RegExp object /\S+@(\S+\.\S+)/gi to find all the e-mails in the text. The g flag makes the search global and the i flag makes it case-insensitive. The \S+ part of the pattern matches one or more non-whitespace characters. The @ matches the @ symbol. The (\S+\.\S+) part of the pattern matches one or more non-whitespace characters, followed by a period, followed by one or more non-whitespace characters. The parentheses around this part of the pattern make it a capture group.

Then you used the $1 replacement string to replace the e-mails with the capture group. The $1 replacement string refers to the first capture group in the pattern. In this case, the first capture group is the e-mail domain. So the result is that you replaced all the e-mails with their domains.

Find and Replace Strings With Regex and Callback Functions

You can also use a callback function to replace strings with regular expressions. This is useful when you need to perform more complex replacements, perhaps with additional logic. For example, you may want to redact a list of emails stripping the username, and removing the email if it's not from a certain list.

To use a callback function, you need to pass a replacer function as the second argument to the .replaceAll() method. You can also use the .replace() method and it works in the same way.

The replacer function signature, or the arguments it accepts depends on your regular expression. If your regular expression has no capture groups, then the replacer function accepts four arguments: the match, the offset, the original string, and a groups object.

If your regular expression has capture groups, then the replacer function accepts more arguments that correspond to the number of capture groups: the match, the capture groups, the offset, the original string, and a groups object.

let clients = ["lemon-aid", "eggnogemporium"];
let text =
  "[email protected], [email protected], [email protected]";

function replacer(match, domainCaptureGroup, offset, string, groups) {
  for (let i = 0; i < clients.length; i++) {
    if (domainCaptureGroup.includes(clients[i])) {
      return domainCaptureGroup;
    }
  }
  return "";
}

text.replaceAll(/\S+@(\S+\.\S+)/gi, replacer);
// lemon-aid.io,  eggnogemporium.net

Neat! You've replaced all the e-mails with their domains, but only if the domain is in the clients array. If the domain is not in the clients array, then you replaced it with an empty string.

Note that if you have more capture groups in your regular expression, then you need to add more arguments to your replacer function. For example, if you have two capture groups, then your replacer function needs to accept six arguments: the match, the first capture group, the second capture group, the offset, the original string, and a groups object.

It's also worth noting that if you don't intend to use the offset, string, or groups arguments, then you can omit them from your replacer function:

function replacer(match, domainCaptureGroup) {
  for (let i = 0; i < clients.length; i++) {
    if (domainCaptureGroup.includes(clients[i])) {
      return domainCaptureGroup;
    }
  }
  return "";
}
Colorful illustration of a light bulb

Here's a more advanced and idiomatic way to write the above code:

let clients = ["lemon-aid", "eggnogemporium"];
let text =
"[email protected], [email protected], [email protected]";

text.replaceAll(/\S+@(\S+\.\S+)/gi, (match, domainCaptureGroup) => {
return clients.some((client) => domainCaptureGroup.includes(client))
? domainCaptureGroup
: "";
});
// lemon-aid.io,  eggnogemporium.net

This code:

  • Uses an inline arrow function expressions instead of defining the replacer function separately.
  • Uses the .some() array method to go through the array to check if any of the clients are in the domain.
  • .some() is used with another arrow function with the .includes() string method.
  • Uses the ternary operator to return the domain or an empty string.

All these concepts will be covered in later lessons in the curriculum, except for the ternary operator and .includes() method, which were covered in earlier lessons.

Summary: How to Replace Strings in Javascript

In this lesson, you've delved into the versatile world of string replacement in JavaScript, gaining valuable skills for text manipulation.

  • You've learned the basics of string replacement with the .replace() method in JavaScript, understanding how to substitute specific parts of a string.
  • You've discovered .replaceAll(), a method that extends your capability to replace every instance of a specified string, enhancing your text processing skills.
  • You've become familiar with using regular expressions in combination with .replace() and .replaceAll(), enabling you to perform more complex and pattern-based replacements.
  • You've explored the use of the g (global) and i (case-insensitive) flags in regular expressions, which broaden your scope in searching and replacing text.
  • You've practiced using capture groups in regular expressions, a powerful tool for manipulating and reformatting parts of your strings.
  • You've learned how to use callback functions with .replace() and .replaceAll(), which opens up possibilities for more dynamic and logic-driven string replacements.

You've significantly enhanced your JavaScript toolkit, equipping yourself to handle a wide range of text manipulation tasks.