javascript - 如何使用javascript仅删除字符串中的html标签

标签 javascript jquery html string

我想使用 javascript 从给定的字符串中删除 html 标签。我研究了当前的方法,但其中出现了一些 Unresolved 问题。

目前的解决方案

(1) 使用javascript,创建虚拟div标签并获取文本

  function remove_tags(html)
  {
       var tmp = document.createElement("DIV");
       tmp.innerHTML = html; 
       return tmp.textContent||tmp.innerText; 
  }

(2) 使用正则表达式

  function remove_tags(html)
  {
       return html.replace(/<(?:.|\n)*?>/gm, '');
  }

(3) 使用JQuery

  function remove_tags(html)
  {
       return jQuery(html).text();
  }

这三种方案都可以正常工作,但是如果字符串是这样

  <div> hello <hi all !> </div>

剥离的字符串就像 hello .但我只需要删除 html 标签。喜欢hello <hi all !>

已编辑:背景是,我想删除特定文本区域的所有用户输入 html 标签。但是我想让用户输入<hi all>一种文字。在当前方法中,它会删除 <> 中包含的所有内容。

最佳答案

如果您考虑其他方法,使用正则表达式可能不是问题。例如,查找所有标签,然后检查标签名称是否与已定义的有效 HTML 标签名称列表相匹配:

var protos = document.body.constructor === window.HTMLBodyElement;
    validHTMLTags  =/^(?:a|abbr|acronym|address|applet|area|article|aside|audio|b|base|basefont|bdi|bdo|bgsound|big|blink|blockquote|body|br|button|canvas|caption|center|cite|code|col|colgroup|data|datalist|dd|del|details|dfn|dir|div|dl|dt|em|embed|fieldset|figcaption|figure|font|footer|form|frame|frameset|h1|h2|h3|h4|h5|h6|head|header|hgroup|hr|html|i|iframe|img|input|ins|isindex|kbd|keygen|label|legend|li|link|listing|main|map|mark|marquee|menu|menuitem|meta|meter|nav|nobr|noframes|noscript|object|ol|optgroup|option|output|p|param|plaintext|pre|progress|q|rp|rt|ruby|s|samp|script|section|select|small|source|spacer|span|strike|strong|style|sub|summary|sup|table|tbody|td|textarea|tfoot|th|thead|time|title|tr|track|tt|u|ul|var|video|wbr|xmp)$/i;

function sanitize(txt) {
    var // This regex normalises anything between quotes
        normaliseQuotes = /=(["'])(?=[^\1]*[<>])[^\1]*\1/g,
        normaliseFn = function ($0, q, sym) { 
            return $0.replace(/</g, '&lt;').replace(/>/g, '&gt;'); 
        },
        replaceInvalid = function ($0, tag, off, txt) {
            var 
                // Is it a valid tag?
                invalidTag = protos && 
                    document.createElement(tag) instanceof HTMLUnknownElement
                    || !validHTMLTags.test(tag),

                // Is the tag complete?
                isComplete = txt.slice(off+1).search(/^[^<]+>/) > -1;

            return invalidTag || !isComplete ? '&lt;' + tag : $0;
        };

    txt = txt.replace(normaliseQuotes, normaliseFn)
             .replace(/<(\w+)/g, replaceInvalid);

    var tmp = document.createElement("DIV");
    tmp.innerHTML = txt;

    return "textContent" in tmp ? tmp.textContent : tmp.innerHTML;
}

Working Demo: http://jsfiddle.net/m9vZg/3/

这是有效的,因为浏览器将 '>' 解析为文本,如果它不是匹配的 '<' 开始标记的一部分。它不会遇到与尝试使用正则表达式解析 HTML 标签相同的问题,因为您只是在寻找开始定界符和标签名称,其他一切都不相关。

它也是面向 future :WebIDL 规范告诉 vendor 如何实现 HTML 元素的原型(prototype),因此我们尝试从当前匹配的标签创建 HTML 元素。如果该元素是 HTMLUnknownElement 的实例,我们就知道它不是有效的 HTML 标记。 validHTMLTags 正则表达式为未实现这些原型(prototype)的旧浏览器(例如 IE 6 和 7)定义了 HTML 标记列表。

关于javascript - 如何使用javascript仅删除字符串中的html标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17164335/

相关文章:

html - 使用 localhost URL 在浏览器中打开页面的 node.js 代码

Javascript getElementByID().innerHTML() 不工作

javascript - 如何在 JavaScript 中对 Promise 'then' 的结果进行单元测试?

javascript - 如何在 react 循环中设置动态复选框的状态?

c# - 使用 jQuery 动态添加行后计算 C# 中的行数

javascript - 如何在 JavaScript 中调用 HTML 选择值?

javascript - 尽管遵循了严格的说明,但仍看到未定义的 "Uncaught TypeError: Cannot read property ' 重量

ajax - select2与ajax post方法

css - 在另一个 Div 中以表格方式 float 的 Div

html - 有什么方法可以使用 CSS 在 Outlook 中将图像设置为原始大小的 100%?