![](/img/trans.png)
[英]how to remove HTML tags from a string in JavaScript without using regexp?
[英]How to remove only html tags in a string using javascript
我想使用javascript从给定的字符串中删除html标签。 我研究了当前的方法,但是它们出现了一些未解决的问题。
现有解决方案
(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;
}
工作演示: http : //jsfiddle.net/m9vZg/3/
这是因为浏览器将“>”解析为文本,如果它不是匹配的“<”开始标记的一部分。 它没有遇到与尝试使用正则表达式解析HTML标记相同的问题,因为您只是在寻找开始分隔符和标记名称,其他一切都无关紧要。
它也是未来的证明 :WebIDL规范告诉供应商如何实现HTML元素的原型,因此我们尝试从当前匹配的标记创建一个HTML元素。 如果元素是HTMLUnknownElement
的实例,我们知道它不是有效的HTML标记。 validHTMLTags
正则表达式为不实现这些原型的旧浏览器(例如IE 6和7)定义HTML标记列表。
var StrippedString = OriginalString.replace(/(<([^>]+)>)/ig,"");
这是我的解决方案,
function removeTags(){
var txt = document.getElementById('myString').value;
var rex = /(<([^>]+)>)/ig;
alert(txt.replace(rex , ""));
}
我使用正则表达式来防止我的textarea中的HTML标记
<form>
<textarea class="box"></textarea>
<button>Submit</button>
</form>
<script>
$(".box").focusout( function(e) {
var reg =/<(.|\n)*?>/g;
if (reg.test($('.box').val()) == true) {
alert('HTML Tag are not allowed');
}
e.preventDefault();
});
</script>
<script type="text/javascript">
function removeHTMLTags() {
var str="<html><p>I want to remove HTML tags</p></html>";
alert(str.replace(/<[^>]+>/g, ''));
}</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.