【问题标题】:How to remove HTML tags in JavaScript, but holding the character "<" when ther's not the character ">"如何在 JavaScript 中删除 HTML 标记,但在没有字符 \">\" 时保留字符 \"<\"
【发布时间】:2022-11-01 17:51:24
【问题描述】:

当标签没有关闭而不替换 HTML 字符时,有一种方法可以在 Javascript 中解析 HTML 中的字符 &lt;

谈论像&lt;html&gt;efrferrefrer&lt;wedw 这样的字符串。

它必须回馈efrferrefrer&lt;wedw

尝试

    function removeHtmlTags(input){
        let tmp = document.createElement("div");
        tmp.innerHTML = input;
        return tmp.textContent || tmp.innerText || "";
    }
    //or
    function removeHtmlTags(input){
        return input.replace(/<[^>]*>?/gm, '');
    }

没有给出预期的结果。

它消除了“<wedw”。

所以,有一种方法可以做到这一点不使用替换 html 字符的函数喜欢

    function escapeHtml(text) {
        var map = {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#039;'
        };
        return = text.replace(/[&<>"']/g, function(m) { return map[m]; });
    }

它必须完全是efrferrefrer&lt;wedw

【问题讨论】:

    标签: javascript html html-parsing


    【解决方案1】:

    我不确定我是否理解正确,但我认为你需要这个

    const p = '<html>efrferrefrer<wedw';
    const regex = /<[A-Z]+>{1}/igm;
    console.log(p.replace(regex, ''));
    
    const p2 = '<html>efrferrefrer<wedw<html><html>';
    console.log(p2.replace(regex, ''));

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-08
      • 1970-01-01
      • 2011-05-13
      • 2012-10-08
      • 1970-01-01
      • 2019-07-31
      • 1970-01-01
      相关资源
      最近更新 更多