我想使用 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, '<').replace(/>/g, '>');
},
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 ? '<' + 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/