Skip to content

Find and Replace String Methods 2

A find-and-replace feature takes two pieces of text from the user and swaps every occurrence of the first for the second. The string work is one call to replaceAll(), which find and replace strings introduces. The care goes into the input, because a user can type an empty search, a replacement that contains the search text, or characters that mean something in a regular expression.

Keeping the string logic in a function of its own makes it easy to test away from the page.

function replaceEvery(text, find, replacement) {
if (find === '') return text;
return text.replaceAll(find, replacement);
}
console.log(replaceEvery('red, green, red', 'red', 'blue'));
console.log(replaceEvery('a-b-c', '-', '--'));
console.log(replaceEvery('abc', '', '*'));
console.log('abc'.replaceAll('', '*'));

This prints:

blue, green, blue
a--b--c
abc
*a*b*c*

The guard matters because an empty string matches at every position, so replaceAll('', '*') puts the replacement between every pair of characters, as the last line shows.

Before replaceAll() existed, a common approach was to call replace() in a loop while the text still contained the search string. That loop never ends when the replacement contains the search text, because each pass puts a new match back in. The example stops itself after five passes to show the effect.

let text = 'a-b-c';
let passes = 0;
while (text.includes('-') && passes < 5) {
text = text.replace('-', '--');
passes++;
}
console.log(passes, text);

This prints:

5 a------b-c

replaceAll() scans the original text once, so it has no such problem.

replaceAll() with plain text is case-sensitive. To ignore case, the search text has to become a regular expression with the g and i flags. Characters such as +, . and ( have special meanings in a regular expression, so the user’s text has to be escaped first. RegExp.escape(), added in ES2025 and supported in current browsers and recent versions of Node.js, does that.

const find = 'c++';
const pattern = new RegExp(RegExp.escape(find), 'gi');
console.log('I write C++ and c++ daily'.replace(pattern, 'Rust'));
try {
new RegExp(find, 'gi');
} catch (error) {
console.log(`${error.name}: ${error.message}`);
}

This prints:

I write Rust and Rust daily
SyntaxError: Invalid regular expression: /c++/gi: Nothing to repeat

Without escaping, the same input throws an error, and other input could match text the user never meant.

The page needs a form with two text boxes and an element holding the text to change.

<form id="find-form">
<input id="find-text" placeholder="Find" required>
<input id="replace-text" placeholder="Replace with">
<button>Replace all</button>
</form>
<p class="target">The quick brown fox jumps over the lazy dog. The dog sleeps.</p>

The script listens for the form’s submit event rather than the button’s click event, so pressing Enter in a text box works too. preventDefault() stops the browser from reloading the page.

const form = document.querySelector('#find-form');
const target = document.querySelector('.target');
form.addEventListener('submit', (event) => {
event.preventDefault();
const find = document.querySelector('#find-text').value;
const replacement = document.querySelector('#replace-text').value;
target.textContent = replaceEvery(target.textContent, find, replacement);
});

Typing dog and cat and pressing Replace all changes both dogs in the paragraph to cats. Assigning to textContent replaces everything inside the element with plain text, so any links or bold text inside the paragraph would be lost. For marked-up content, apply the same function to each text node in turn, which a TreeWalker created with document.createTreeWalker() can visit.

Steve Griffith covers this topic in his video Find and Replace Strings with JavaScript.