tôi đã làm việc trên đề nghị cuối cùng để phát triển một chức năng xóa tất cả hoặc chỉ giữ một số thẻ
function strip_tags(_html /*you can put each single tag per argument*/)
{
var _tags = [], _tag = "" ;
for(var _a = 1 ; _a < arguments.length ; _a++)
{
_tag = arguments[_a].replace(/<|>/g, '').trim() ;
if (arguments[_a].length > 0) _tags.push(_tag, "/"+_tag);
}
if (!(typeof _html == "string") && !(_html instanceof String)) return "" ;
else if (_tags.length == 0) return _html.replace(/<(\s*\/?)[^>]+>/g, "") ;
else
{
var _re = new RegExp("<(?!("+_tags.join("|")+")\s*\/?)[^>]+>", "g");
return _html.replace(_re, '');
}
}
var _html = "<b>Just</b> some <i>tags</i> and text to test <u>this code</u>" ;
document.write("This is the original html code including some tags<br>");
document.write(_html + "<br><br>"); // original html code
document.write("Now we remove all tags (plain text)<br>");
document.write(strip_tags(_html) + "<br><br>"); // remove all tags
document.write("Only the bold tag is kept<br>");
document.write(strip_tags(_html, "b") + "<br><br>"); // keep <b> only
document.write("Only the underline tag is kept<br>");
document.write(strip_tags(_html, "u") + "<br><br>"); // keep <u> only
document.write("Only the italic tag is kept<br>");
document.write(strip_tags(_html, "<i>") + "<br><br>"); // keep <i> only
document.write("Keeping both italic and underline<br>");
document.write(strip_tags(_html, "i", "u")); // keep both <i> and <u>
Nguồn
2016-02-01 10:34:36
nếu không có
bất cứ nơi nào, chỉ cần loại bỏ các thẻ html khác. – cp100
Ngay cả khi được mở, đây là bản sao của [this one] (http://stackoverflow.com/a/828647/263858) và [this one] (http://stackoverflow.com/a/18128321/263858) –
Có thể trùng lặp của [Dải Html từ Văn bản trong JavaScript ngoại trừ thẻ p?] (Https://stackoverflow.com/questions/828572/strip-html-from-text-in-javascript-except-p-tags) – Wolfie