Skip to main content

JavaScript Strings

JavaScript String replace

Written by Published

replace swaps one piece of text for another and returns a new string.

By default it only changes the first match.

replaceAll changes every one, which is usually what people expect.

Example

Example

javascript

const text = "cat cat cat";

console.log(text.replace("cat", "dog"));

Only the first cat changed.

replace and replaceAll

replace changes the first match only.

replaceAll changes every match.

Both return a new string and leave the original alone.

Syntax

Syntax

javascript

text.replace(find, replaceWith);
text.replaceAll(find, replaceWith);

Both are case sensitive.

Replacing Everything

This is the fix for the surprise above.

Example

Example

javascript

const text = "cat cat cat";

console.log(text.replaceAll("cat", "dog"));

All three changed.

The Original Is Untouched

As with every string method, the result must be used.

Example

Example

javascript

const text = "hello";

text.replace("hello", "goodbye");

console.log(text);

The output is still hello.

Removing Text

Replacing with an empty string deletes it.

Example

Example

javascript

const phone = "07-123-456";

console.log(phone.replaceAll("-", ""));

The output is 07123456.

Case Matters

A different case is a different string, so it will not match.

Example

Example

javascript

const text = "Cat";

console.log(text.replace("cat", "dog"));
console.log(text.toLowerCase().replace("cat", "dog"));

The first found nothing to change.

Tidying User Input

Chaining a few calls cleans text up nicely.

Example

Example

javascript

const messy = "  Ada   Lovelace  ";

const tidy = messy.trim().replaceAll("   ", " ");

console.log(tidy);

A regular expression handles any amount of spacing, covered later.

Complete Example

Complete Example

html

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript String replace</title>
</head>
<body>

  <h1>String replace</h1>

  <p id="out"></p>

  <script>
    const text = "cat cat cat";
    const phone = "07-123-456";

    document.getElementById("out").innerHTML =
      "First only: " + text.replace("cat", "dog") +
      "<br>All of them: " + text.replaceAll("cat", "dog") +
      "<br>Digits only: " + phone.replaceAll("-", "");
  </script>

</body>
</html>

Try It Yourself

Run the above example in the Try It Editor.

Try removing instead:

Replace with an empty string and see the text disappear.

Important Points

  • replace changes only the first match.
  • replaceAll changes every match.
  • Both return a new string.
  • Replacing with an empty string removes text.
  • Both are case sensitive.

Conclusion

replaceAll is usually the one you actually want.

Remember to use the returned value.

For patterns rather than exact text, regular expressions take over.