JavaScript Replace Text

April 26, 2020
Written By Spida C

Exploring how creativity, culture, and technology connect us.

If you ever get into a situation where a string is received with some text that either shouldn’t be there, or is in there incorrectly, here’s a quick solution for that, use String.replace():

var text = "What the for an example";

alert("Before: " + text);


if (text && text.includes("What the")){
	text = text.replace("What the","Text");
}

alert("After: " + text);

The Basics: String.replace()

The replace() method is the most common way to replace text in JavaScript. It takes two arguments: the pattern to find and the replacement string.

const str = 'Hello World';
const result = str.replace('World', 'JavaScript');
console.log(result); // 'Hello JavaScript'

Important: replace() only replaces the first occurrence by default. This trips up beginners constantly. If your string contains multiple instances of the search term, only the first one gets replaced.

Replacing All Occurrences

There are three ways to replace all occurrences of a substring:

1. replaceAll() (Modern Approach)

const str = 'foo bar foo baz foo';
const result = str.replaceAll('foo', 'qux');
console.log(result); // 'qux bar qux baz qux'

The replaceAll() method was introduced in ES2021 and is supported in all modern browsers. Check the MDN documentation for replaceAll() for full details and browser compatibility.

2. Regex with Global Flag

const str = 'foo bar foo baz foo';
const result = str.replace(/foo/g, 'qux');
console.log(result); // 'qux bar qux baz qux'

The /g flag (global) tells the regex engine to find and replace all matches, not just the first one. This is the classic approach that works in all JavaScript environments.

3. split() and join()

const str = 'foo bar foo baz foo';
const result = str.split('foo').join('qux');
console.log(result); // 'qux bar qux baz qux'

This technique splits the string at every occurrence of the search term, then joins the pieces back with the replacement. It works everywhere but is less readable than the other approaches.

Case-Insensitive Replacement

To replace text regardless of case, use a regex with the i (case-insensitive) flag:

const str = 'Hello HELLO hello';
const result = str.replace(/hello/gi, 'hi');
console.log(result); // 'hi hi hi'

Note the use of both g (global) and i (case-insensitive) flags together.

Using Functions as Replacements

One of the most powerful features of replace() is the ability to pass a function as the second argument. The function receives the matched text and can return a dynamic replacement:

const str = 'prices: $10, $25, $100';
const result = str.replace(/\$(\d+)/g, (match, amount) => {
  return '$' + (parseInt(amount) * 1.1).toFixed(2);
});
console.log(result); // 'prices: $11.00, $27.50, $110.00'

This technique is invaluable for template processing, data transformation, and text formatting tasks.

Replacing Text in the DOM

To replace text content in HTML elements, use textContent or innerHTML:

// Safe text replacement (no HTML parsing)
element.textContent = element.textContent.replace('old', 'new');

// HTML-aware replacement (be careful with user input)
element.innerHTML = element.innerHTML.replace('old', 'new');

Security warning: Never use innerHTML with user-supplied replacement strings — this creates XSS (cross-site scripting) vulnerabilities. Always use textContent for user-generated content.

Common Pitfalls

  • Strings are immutable: replace() returns a new string; it doesn’t modify the original
  • Special regex characters: If your search term contains . * + ? ^ $ { } ( ) | [ ] \, you need to escape them with a backslash
  • replaceAll() with regex: If you pass a regex to replaceAll(), it must include the g flag or it throws a TypeError

For more JavaScript tutorials and web development guides, explore the GTWebs blog.

Leave a Comment