简体   繁体   中英

JavaScript: Remove HTML Tags, Modify Tags/Text, and Insert Tags Back In

I am trying to find a way to remove all tags in an HTML document, store their location, modify the remaining text, then reinsert the tags where they belong.

Key Points

  • I need to insert the tags back in again later, thus I need to store the location of each tag
    • Therefore, DOMParser as suggested here will not work
  • This will be done on external websites, not my own
  • The regex suggested here ( /<(?:.|\\n)*?>/gm ) will work, but it also falsely captures < or > included the html
  • It seems this works: https://regexr.com/3npgn ( /<[^<|>]*>/g ), but I read that using regex is not a great way to parse html. Are there cases where this would fail?

The full code:

function foo() {
    var elementHtml = document.body.innerHTML;
    var tags = [];
    var tagLocations = [];
    //var htmlTagRegEx =/<{1}\/{0,1}\w+>{1}/;
    var htmlTagRegEx =/<[^<]*>/;

    //Strip the tags from the elementHtml and keep track of them
    var htmlTag;
    while (htmlTag = elementHtml.match(htmlTagRegEx)) {
        console.log('htmlTag: ', htmlTag);
        tagLocations[tagLocations.length] = elementHtml.search(htmlTagRegEx);
        tags[tags.length] = htmlTag;
        elementHtml = elementHtml.replace(htmlTag, '');
    }
}

EDIT

To avoid confusion, here follows a detailed explanation of what I want to accomplish:

Search for a string in the text of a whole (external) website (not including the tags), then change the styling (eg color) of those instances if found.

Here is my attempt:

    function highlightInElement(elementId, text) {
        var elementHtml = document.body.innerHTML;
        var tags = [];
        var tagLocations = [];
        //var htmlTagRegEx =/<{1}\/{0,1}\w+>{1}/;
        var htmlTagRegEx =/<[^<]*>/;
        //Strip the tags from the elementHtml and keep track of them
        var htmlTag;
        while (htmlTag = elementHtml.match(htmlTagRegEx)) {
            //console.log('htmlTag: ', htmlTag);
            tagLocations[tagLocations.length] = elementHtml.search(htmlTagRegEx);
            tags[tags.length] = htmlTag;
            elementHtml = elementHtml.replace(htmlTag, '');
        }
        console.log('elementHtml: ', elementHtml);

        //Search for the text in the stripped html
        var textLocation = elementHtml.search(text);
        if (textLocation) {
            //Add the highlight
            var highlightHTMLStart = '<span class="highlight">';
            var highlightHTMLEnd = '</span>';
            elementHtml = elementHtml.replace(text, highlightHTMLStart + text + highlightHTMLEnd);

            //plug back in the HTML tags
            var textEndLocation = textLocation + text.length;
            for (let i = tagLocations.length - 1; i >= 0; i--) {
                var location = tagLocations[i];
                if (location > textEndLocation) {
                    location += highlightHTMLStart.length + highlightHTMLEnd.length;
                } else if (location > textLocation) {
                    location += highlightHTMLStart.length;
                }
                elementHtml = elementHtml.substring(0, location) + tags[i] + elementHtml.substring(location);
            }
        }

        //Update the html of the element
        document.body.innerHTML = elementHtml;
    }

    highlightInElement(document.documentElement, fooInputTxt.value);

To avoid confusion, here follows a detailed explanation of what I want to accomplish: Search for a string in the text of a whole (external) website (not including the tags), then change the styling (eg color) of those instances if found.

Then that's exactly what you should do :)

First, build a recursive function to traverse the DOM and get all the text nodes:

function findTextNodes(node, ret) {
    var c = node.childNodes, i, l = c.length;
    for( i=0; i<l; i++) {
        switch(c[i].nodeType) {
            case 1: // element node
                findTextNodes(c[i], ret);
                break;
            case 3: // text node
                ret.push(c[i]);
                break;
        }
    }
}
var textNodes = [];
findTextNodes(document.body, textNodes);

Now that you have an array of all the text nodes in the document, you can begin searching them for your target.

function searchTextNodes(nodes, search) {
    var results = [], l = nodes.length, i,
        regex = new RegExp(search,'i'), match,
        span;
    for( i=0; i<l; i++) {
        while( (match = nodes[i].nodeValue.search(regex)) > -1) {
            nodes[i] = nodes[i].splitText(match);
            span = document.createElement('span');
            span.classList.add('highlight');
            nodes[i].parentNode.insertBefore(span, nodes[i]);
            nodes[i].splitText(search.length);
            span.appendChild(nodes[i]);
            nodes[i] = span.nextSibling;
        }
    }
}
searchTextNodes(textNodes, fooInputTxt.value);

And... that's it! For extra credit, here's how to "undo" the search:

function undoSearch(root) {
    var nodes = root.querySelectorAll("span.highlight"),
        l = nodes.length, i;
    for( i=0; i<l; i++) {
        nodes[i].parentNode.replaceChild(nodes[i].firstChild, nodes[i]);
    }
    root.normalize();
}
undoSearch(document.body);

Demo on JSFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM