Case-insensitive match with case-sensitive replacement
When you need a global search and replace of some text but you want to maintain the case of the original match.
by clarmond
HTML
<h1>Before</h1>
<div id='before' class='text'> </div>
<h1>After</h1>
<div id='after' class='text'> </div>
CSS
body {
font-family: Arial, Helvetica, Sans-Serif;
}
h1 {
font-size: 16pt;
}
.text {
background-color: #eee;
border: 1px solid #ccc;
border-radius: 8px;
margin-bottom: 40px;
padding: 10px;
}
.highlight {
background-color: #ffa;
border-radius: 2px;
padding: 2px 4px;
}
JavaScript
let sampleText = 'This is my sample text: test Test TEST';
const searchText = 'test';
document.getElementById('before').innerHTML = sampleText;
const pattern = new RegExp(searchText, 'ig');
const matches = sampleText.match(pattern, sampleText);
if (matches !== null) {
matches.forEach((match) => {
sampleText = sampleText.replace(match, `<span class="highlight">${match}</span>`);
});
}
document.getElementById('after').innerHTML = sampleText;