有没有一种简单的方法可以在JavaScript中获取一个html字符串并去掉html?
当前回答
这是一个解决@MikeSamuel安全问题的版本:
function strip(html)
{
try {
var doc = document.implementation.createDocument('http://www.w3.org/1999/xhtml', 'html', null);
doc.documentElement.innerHTML = html;
return doc.documentElement.textContent||doc.documentElement.innerText;
} catch(e) {
return "";
}
}
注意,如果HTML标记不是有效的XML,它将返回一个空字符串(也就是,标记必须关闭,属性必须引用)。这并不理想,但确实避免了潜在的安全漏洞问题。
如果不需要有效的XML标记,可以尝试使用:
var doc = document.implementation.createHTMLDocument("");
但出于其他原因,这也不是一个完美的解决方案。
其他回答
很多人已经回答了这个问题,但我认为分享我编写的函数可能会有用,该函数可以从字符串中删除HTML标记,但允许您包含一个不希望删除的标记数组。它很短,对我来说一直很好。
function removeTags(string, array){
return array ? string.split("<").filter(function(val){ return f(array, val); }).map(function(val){ return f(array, val); }).join("") : string.split("<").map(function(d){ return d.split(">").pop(); }).join("");
function f(array, value){
return array.map(function(d){ return value.includes(d + ">"); }).indexOf(true) != -1 ? "<" + value : value.split(">")[1];
}
}
var x = "<span><i>Hello</i> <b>world</b>!</span>";
console.log(removeTags(x)); // Hello world!
console.log(removeTags(x, ["span", "i"])); // <span><i>Hello</i> world!</span>
简单的2行jquery去掉html。
var content = "<p>checking the html source </p><p>
</p><p>with </p><p>all</p><p>the html </p><p>content</p>";
var text = $(content).text();//It gets you the plain text
console.log(text);//check the data in your console
cj("#text_area_id").val(text);//set your content to text area using text_area_id
我对Jibberboy 2000的原始脚本做了一些修改希望对某人有用
str = '**ANY HTML CONTENT HERE**';
str=str.replace(/<\s*br\/*>/gi, "\n");
str=str.replace(/<\s*a.*href="(.*?)".*>(.*?)<\/a>/gi, " $2 (Link->$1) ");
str=str.replace(/<\s*\/*.+?>/ig, "\n");
str=str.replace(/ {2,}/gi, " ");
str=str.replace(/\n+\s*/gi, "\n\n");
来自CSS技巧:
https://css-tricks.com/snippets/javascript/strip-html-tags-in-javascript/
常量原始字符串=`<div><p>嘿,这是什么东西</p></div>`;conststripedString=originalString.replace(/(<([^>]+)>)/gi,“”);console.log(strippedString);
最简单的方法:
jQuery(html).text();
它从html字符串中检索所有文本。