有没有一种简单的方法可以在JavaScript中获取一个html字符串并去掉html?
当前回答
输入元素仅支持单行文本:
文本状态表示元素值的单行纯文本编辑控件。
function stripHtml(str) {
var tmp = document.createElement('input');
tmp.value = str;
return tmp.value;
}
更新:这是预期的
function stripHtml(str) {
// Remove some tags
str = str.replace(/<[^>]+>/gim, '');
// Remove BB code
str = str.replace(/\[(\w+)[^\]]*](.*?)\[\/\1]/g, '$2 ');
// Remove html and line breaks
const div = document.createElement('div');
div.innerHTML = str;
const input = document.createElement('input');
input.value = div.textContent || div.innerText || '';
return input.value;
}
其他回答
我想分享一下Shog9批准答案的编辑版本。
正如Mike Samuel在评论中指出的那样,该函数可以执行内联javascript代码。但Shog9说“让浏览器为你做……”是对的
所以…这里是我的编辑版本,使用DOMParser:
function strip(html){
let doc = new DOMParser().parseFromString(html, 'text/html');
return doc.body.textContent || "";
}
这里是测试内联javascript的代码:
strip("<img onerror='alert(\"could run arbitrary JS here\")' src=bogus>")
此外,它不会在解析时请求资源(如图像)
strip("Just text <img src='https://assets.rbl.ms/4155638/980x.jpg'>")
我只需要去掉<a>标签,并用链接的文本替换它们。
这似乎很有效。
htmlContent= htmlContent.replace(/<a.*href="(.*?)">/g, '');
htmlContent= htmlContent.replace(/<\/a>/g, '');
简单的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
这个包非常适合剥离HTML:https://www.npmjs.com/package/string-strip-html
它可以在浏览器和服务器(例如Node.js)上工作。
要获得更简单的解决方案,请尝试此=>https://css-tricks.com/snippets/javascript/strip-html-tags-in-javascript/
var StrippedString = OriginalString.replace(/(<([^>]+)>)/ig,"");