Overview
I’ve created a basic text editor with a “Replace all” feature. However, I’m facing an issue where the output indicates replacements were made even when the text remains unchanged. Here’s a simplified version of my code:
const textarea = document.getElementById('textarea');
const searchInput = document.getElementById('search');
const replaceInput = document.getElementById('replace');
const output = document.getElementById('output');
const replaceButton = document.getElementById('replaceAll');
replaceButton.addEventListener('click', () => {
const searchValue = searchInput.value;
const replaceValue = replaceInput.value;
if (!searchValue) {
output.textContent = 'No search term';
return;
}
const regex = new RegExp(searchValue, 'g');
const matches = textarea.value.match(regex);
if (matches) {
const count = matches.length;
textarea.value = textarea.value.replace(regex, replaceValue);
output.textContent = `${count} replacement${count === 1 ? '' : 's'}`;
} else {
output.textContent = 'No matches';
}
});
textarea {
width: 100%;
height: 100px;
}
#output {
color: #666;
}
<textarea id="textarea">apple orange apple orange</textarea>
<input type="text" id="search" placeholder="Search">
<input type="text" id="replace" placeholder="Replace">
<button id="replaceAll">Replace all</button>
<div id="output"></div>
Edge cases
Non-regex search
- Text: apple orange apple orange
- Search: apple
- Replacement: apple
- Expected output: “No replacement”
- Current output: “2 replacements”
Regex search
- Text: 9/1/2021, 3/1/2022
- Search: (\d*)/\d*/(\d{4})
- Replacement: $1/1/$2
- Expected output: “No replacement”
- Current output: “2 replacements”
Question
How can I modify the code to correctly handle these edge cases and display “No replacement” when the text remains unchanged after the replacement operation?