Menu Home

String.replaceAll()

Hi everyone, and welcome to another exciting edition of Boring JavaScript! Today, we tackle the String.replaceAll() method, which will search the entire string and return a new string with all the matching strings replaced.

Don’t like to read? Then watch our video.

The Replacements

If you ever used String.replace(), you know that it will only replace the first occurrence of the found string, and not every occurrence. To do that, you had to use a regular expression with the ‘global’ flag.

const myString = "Grumpy and Sleepy and Doc and Dopey";
const replaceString = myString.replace('and', 'or');
console.log(replaceString);
// doing a global replace means using RegEx with the 'g' (or global) flag
const regexReplaceString = myString.replace(/and/g, 'or');
console.log(regexReplaceString);

/* output
Grumpy or Sleepy and Doc and Dopey
Grumpy or Sleepy or Doc or Dopey
*/

Not very helpful, especially if you don’t know regular expressions.

Well, the JavaScript Higher Ups heard you, and so came up with String.replaceAll() that allows you to do a global replacement of the string without having to use RegEx and the global flag. It’s very easy to use and only takes two arguments – the string to search for in the target string, and the string to replace it with. The result is saved as a new string and the original string is not touched.

Let’s change our example above to see how it works:

const myString = "Grumpy and Sleepy and Doc and Dopey";
const replaceString = myString.replaceAll('and', 'or');
console.log(replaceString);

/* output
Grumpy or Sleepy or Doc or Dopey
*/

And that’s it! All occurrences of the word ‘and’ in the original string are replaced with ‘or’.

Notice something, though. The search is case sensitive. If you wish to use case insensitivity, then you will need to fall back to using RegEx. And … if you use RegEx, you still have to use the ‘g’ flag.

const myString = "Grumpy and Sleepy And Doc and Dopey";
const replaceString = myString.replaceAll(/[Aa]nd/gi, 'or');
console.log(replaceString);

/* output
Grumpy or Sleepy or Doc or Dopey
*/

Functionally Speaking

The second argument doesn’t have to be a string, though. It can also be a function that will return a string.

When you use a function, it will take a variable number of arguments based upon the matched string. Why a variable number? If the matched string is a RegEx that uses capture groups, then you will have extra arguments, one for each of the capture groups. If you do not have capture groups, then the extra arguments are not there. In summary:

  • 1st argument: The string that was matched (normally the first argument in your replaceAll() method)
  • Arguments 2 – n: A listing of strings found if you use capture groups in a RegEx (if the RegEx is the first argument in your replaceAll());
  • Next to last argument: The character offset in the source string in which the match was found.
  • Last argument: The entire source string.

Let’s see how that works.

const myString = "Grumpy and Sleepy And Doc and Dopey";
const newString = "or";

const preserveCase = (match, offset, entireString) => {
    let capitalizedString = newString;
    if (match[0].toUpperCase() === match[0]) {
        capitalizedString = `${capitalizedString[0].toUpperCase()}${capitalizedString.slice(1)}`;
    }
    return capitalizedString;
}
const replaceString = myString.replaceAll(/[Aa]nd/g, preserveCase);
console.log(replaceString);

/* output
Grumpy or Sleepy Or Doc or Dopey
*/

Notice that in Line 11 we now call the replaceAll() method with a function as the second argument. When JavaScript finds a match, it will then call our function with three arguments (there would have been more if we had capture groups in our RegEx). Our function there simply insures that the replacement string retains the case of the matched string.

The Video

Here is a video we did on the subject.

Shameless Plug

You can find us everywhere!

Check out all our videos at: https://www.boringjavascript.com

Check out everything at: https://www.thevirtuoid.com

Facebook: https://www.facebook.com/TheVirtuoid

Twitter: https://twitter.com/TheVirtuoid

YouTube: https://www.youtube.com/channel/UCKZ7CV6fI7xlh7zIE9TWqgw

Categories: Boring JavaScript Javascript

Tagged as:

thevirtuoid

Web Tinkerer. No, not like Tinkerbell.

Creator of the game Virtuoid. Boring JavaScript. Visit us at thevirtuoid.com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: