JSFiddle - React, Tailwind, and code Playground

by der_robert

HTML

<div id="msg">
</div>

JavaScript

function removeScriptAndStyleTags(html) {
    return html.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi, '')
               .replace(/<style[^>]*>([\s\S]*?)<\/style>/gi, '');
}

function removeSelfClosingTags(html) {
    return html.replace(/<[^>]*\/\s?>/gi, '');
}

function removeSpecialTags(html) {
    return html.replace(/<(br|hr|img)[^>]*>/gi, '');
}

function removeTextNodes(html) {
    return html.replace(/^[^<>]+|[^<>]+$/g, '').replace(/(?<=>)[^<>]+(?=<)/g, '');
}

function validHTML(html) {
    html = html.toLowerCase();
    html = removeScriptAndStyleTags(html);
    html = removeSelfClosingTags(html);
    html = removeSpecialTags(html);
    html = removeTextNodes(html);

    let tags = html.split(/(?<=>)(?=<)/);
    let tagStack = [];

    for (let tag of tags) {
        if (tag.startsWith("</")) {
            let closingTag = tag.match(/<\/\s*([\w\-]+)\s*>/)[1];
            if (tagStack.length === 0) {
                console.error("Mismatched closing tag for "+tagStack[tagStack.length - 1]+" found: " + closingTag);
                return false;
            }
            if (tagStack[tagStack.length - 1] !== closingTag) {
                console.error("Falsche Verschachtelung: Erwartet </" + tagStack[tagStack.length - 1] + ">, gefunden </" + closingTag + ">");
                return false;
            }
            tagStack.pop();
        } else {
            let openingTag = tag.match(/<\s*([\w\-]+)/)[1];
            tagStack.push(openingTag);
        }
    }

    if (tagStack.length > 0) {
        console.error("Nicht geschlossene Tags: " + tagStack.join(", "));
        return false;
    }

    return true;
}

// Beispiel
// Example usage
let html = "<html><head><title>Test</title></head><body><div><p>Exampl</div></p></body></html>";
//console.log(validHTML(html));  // should return true */
validHTML(html);

/* function validHTML(html) {
    html = html.toLowerCase();
    html = removeScriptAndStyleTags(html);
    html = removeSelfClosingTags(html);
 ...