I am trying to create a script in Javascript that performs markup functions, similar to the browser's ctr + f function. It shouldn't be difficult, but I have to check four criteria that I check on a switch, the criteria are "Matches", "Starts with" , "Ends with" and "Any position". I'm using the window.find() method, but I seem to be having trouble with it. In other words, I need to be able to highlight "Lor" for the "Starts with" criteria and "em" for the "Ends with" criteria and of course "Lorem" for the "Coincident" criteria.
Can someone help me?
function HighLightText() {
var contentElement = document.getElementById("content");
let word = document.getElementById("word").value;
let className = "search-mark";
let criterial = "Any position"; //Can be "Ends with" | "Starts with" | "Coincident".
let scrollDetail = false;
var searchResults = document.getElementsByClassName(className);
if (window.find && window.getSelection) {
document.designMode = "on";
var sel = window.getSelection();
sel.collapse(document.body, 0);
var listOfWord = [];
switch (criterial) {
case "Coincident":
listOfWord.push(" " + word + "");
listOfWord.push(word + " ");
// ...more cases where the word is found
break;
case "Any position":
listOfWord.push(word);
break;
case "Ends with":
listOfWord.push(word + ".");
listOfWord.push(word + ",");
listOfWord.push(word + "!");
listOfWord.push(word + "?");
// ...more cases where the word is found
break;
case "Starts with":
listOfWord.push(" " + word);
// ...more cases where the word is found
break;
}
listOfWord.forEach(singleWord => {
while (window.find(singleWord)) {
scroll(0, scrollDetail)
document.execCommand("insertHTML", false, '<b><mark>' + window.getSelection().toString() + '</mark></b>');
}
});
sel.collapseToEnd();
document.designMode = "off";
} else if (document.body.createTextRange) {
var textRange = document.body.createTextRange();
textRange.moveToElementText(contentElement);
while (textRange.findText(text)) {
textRange.execCommand("BackColor", false, "yellow");
textRange.collapse(false);
}
}
}
Here is my fiddle: https://jsfiddle.net/MadDev82/97sdn0mr/4/
Thanks!