1 year ago
#380696
Arbaz Khalid
highlight the .replace() word in javascript
function handleTextNode(textNode) {
if(textNode.nodeName !== '#text'
|| textNode.parentNode.nodeName === 'SCRIPT'
|| textNode.parentNode.nodeName === 'STYLE'
) {
//Don't do anything except on text nodes, which are not children
// of or .
return;
}
var find = ["build", "add", "Fast"];
var replace = ["Develope", "add", "Fast"];
let origText = textNode.textContent;
let newHtml = origText.replace(new RegExp("(" + find.map(function(i){return i.replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&")}).join("|") + ")", "g"),function(s){ return replace[ find.indexOf(s)]});
if( newHtml !== origText) {
let newSpan = document.createElement('span');
newSpan.innerHTML = newHtml;
textNode.parentNode.replaceChild(newSpan,textNode);
}
// <span title="Dyslexia is a learning disorder that involves difficulty reading due to problems identifying speech sounds. " style="background-color: yellow"></span>
}
let textNodes = [];
//Create a NodeIterator to get the text nodes in the body of the document
let nodeIter = document.createNodeIterator(document.body,NodeFilter.SHOW_TEXT);
let currentNode;
//Add the text nodes found to the list of text nodes to process.
while(currentNode = nodeIter.nextNode()) {
textNodes.push(currentNode);
}
//Process each text node
textNodes.forEach(function(el){
handleTextNode(el);
});
i want to make the replaced word highlighted. this code will run only for web pages. like i am building a adblocker with a functionality that help dyslexia Student. At the moment it only replace words correctly. can any body help?
javascript
replace
highlight
word-wrap
regexp-replace
0 Answers
Your Answer