Replace the first or all matches in a JavaScript string
text.replace(pattern, replacement) returns a string with replacements and leaves the input unchanged. A string search replaces the first match. Use replaceAll() for all occurrences of fixed text, or use a regular expression with g.
Replace the first match with replace()
A string search is case-sensitive. Store the returned value or assign it back to a let variable if you need to use the result. If there is no match, the returned string has the same value. See replace().
const original = 'red blue red';
const changed = original.replace('red', 'green');
console.log(changed); // 'green blue red'
console.log(original); // 'red blue red'
console.log(original.replace('black', 'green')); // same value
Replace all matches and control case sensitivity
For a regular expression, g finds all matches and i ignores case in the example. A regex without g throws TypeError when passed to replaceAll(). A string pattern such as "." matches a literal period, whereas /./g matches most characters. See replaceAll().
const text = 'red blue red';
console.log(text.replaceAll('red', 'green')); // 'green blue green'
console.log('Red red'.replace(/red/gi, 'blue')); // 'blue blue'
Insert dollar signs literally
In a replacement string, $& inserts the matched text. Pass a function that returns the replacement if you want $& to appear literally. An empty string search makes replace() insert at the beginning, so reject an empty query when that behavior would be unexpected. With an empty search, 'ab'.replaceAll('', '-') returns '-a-b-'.
console.log('red'.replace('red', '$&')); // 'red'
console.log('red'.replace('red', () => '$&')); // '$&'
Reorder captured text or transform it with a function
Use $1 and $2 to insert the first and second captured groups. This example swaps the positions of the prefix and digits. Use a function when the result requires a calculation or formatting for each match.
{
const text = 'ITEM-7 ITEM-42';
const pattern = /\b(ITEM)-(\d+)\b/g;
console.log(text.replace(pattern, '$2 ($1)')); // 7 (ITEM) 42 (ITEM)
const padded = text.replace(pattern, (match, prefix, digits) => {
return prefix + '-' + digits.padStart(3, '0');
});
console.log(padded); // ITEM-007 ITEM-042
}
The two outputs are 7 (ITEM) 42 (ITEM) and ITEM-007 ITEM-042. The callback receives the full match, then each captured group. padStart(3, '0') pads short strings and leaves longer values intact. See GetSubstitution.
Try a complete replacement example
Save the full example in UTF-8 as replace-example.html and open it. Compare the first-only and all-matches modes. Try $& as the replacement to see it displayed literally. An empty search shows a message. Reset restores the original fields, and the output uses textContent to display text.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Compare string replacement</title>
</head>
<body>
<label for="source">Original string</label>
<input id="source" type="text" value="red blue red">
<label for="search">Text to find</label>
<input id="search" type="text" value="red">
<label for="replacement">Replacement text</label>
<input id="replacement" type="text" value="green">
<label for="mode">Replacement scope</label>
<select id="mode">
<option value="first">First only: replace()</option>
<option value="all">All: replaceAll()</option>
</select>
<button id="change" type="button">Replace</button>
<button id="reset" type="button">Reset</button>
<pre id="output" aria-live="polite"></pre>
<script>
const source = document.querySelector('#source');
const search = document.querySelector('#search');
const replacement = document.querySelector('#replacement');
const mode = document.querySelector('#mode');
const output = document.querySelector('#output');
function change() {
const original = source.value;
const find = search.value;
const newText = replacement.value;
if (find === '') {
output.textContent = 'Enter the text to find.';
return;
}
const result = mode.value === 'all'
? original.replaceAll(find, () => newText)
: original.replace(find, () => newText);
output.textContent = `Original: ${original}\nResult: ${result}`;
}
document.querySelector('#change').addEventListener('click', change);
document.querySelector('#reset').addEventListener('click', () => {
source.value = 'red blue red';
search.value = 'red';
replacement.value = 'green';
mode.value = 'first';
change();
});
change();
</script>
</body>
</html>




