Saturday, October 15, 2022

Remove mark TAG highlighting search query match

// remove mark TAG function

(function () {
const mark = document.getElementsByTagName('mark');
while (mark.length) {
const parent = mark[0].parentNode;
while (mark[0].firstChild) {
parent.insertBefore(mark[0].firstChild, mark[0]);
}
parent.removeChild(mark[0]);
}
})();

// remove mark TAG with replace()

let str = document.querySelector('main').lastChild.innerHTML;
str = str.replace(/(<mark>|<\/mark>)/g, '');

// failed custom mark TAG functionality

let str = document.querySelector('main').lastChild.innerHTML;
str = str.replace(/<mark>|<\/mark>/g, ''); // remove previous mark
// if NOT, don't mark class names, etc =>
if (
!str.includes(`="${text}`) &&
!str.includes(`__${text}`)
// &&
// !str.includes(`-${text}`)
) {
// remove whitespace, search for all matches (g) and ignore case (i)
let reg = new RegExp(text.trim(), 'gi'); // mark searched text =>
let markTxt = str.replace(reg, (match) => `<mark>${match}</mark>`);
// .replace() does not change the string itself
// it returns a new string
document.querySelector('main').lastChild.innerHTML = markTxt;
document.documentElement
.getElementsByTagName('mark')[0]
.scrollIntoView(); // scroll to first marked instance
}
}
};

https://www.npmjs.com/package/react-highlight-words

https://markjs.io/

No comments:

Post a Comment