![](/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.