<!-- FIND, STYLE AND REPLACE MATCHING STRINGS -->
<script>
const targetStrings = [
{
selector: 'h2',
targetString: 'String 1',
replacementString: 'String 1 replacement',
appendedClassName: 'class-name-here',
},
{
selector: 'p',
targetString: 'String 2',
replacementString: 'String 1 replacement',
appendedClassName: 'class-name-here',
},
]
function wrapAndReplaceMatches(selector, newClass, wordTarget, replacement) {
const pattern = new RegExp(`\\b(${wordTarget})\\b`, 'gi');
const hasClassAttr = newClass ? `class=${newClass}` : ''
const wrapAndReplace = !replacement
? `<span ${hasClassAttr}>$1</span>`
: `<span ${hasClassAttr}>${replacement}</span>`;
Array.from(document.querySelectorAll(selector)).forEach((element) => {
element.innerHTML = element.innerHTML.replace(pattern, wrapAndReplace);
});
}
document.addEventListener('DOMContentLoaded', () => {
targetStrings.forEach(({
selector,
targetString,
replacementString,
appendedClassName
}) => {
wrapAndReplaceMatches(selector, appendedClassName, targetString, replacementString)
})
});
</script>
Quickly copy and paste the code crumbs into your project. If you are not familiar with how this snippet works then click the button below to view the full snippet page.