有没有一种简单的方法可以在JavaScript中获取一个html字符串并去掉html?
当前回答
var STR='<Your HTML STRING>''
var HTMLParsedText="";
var resultSet = STR.split('>')
var resultSetLength =resultSet.length
var counter=0
while(resultSetLength>0)
{
if(resultSet[counter].indexOf('<')>0)
{
var value = resultSet[counter];
value=value.substring(0, resultSet[counter].indexOf('<'))
if (resultSet[counter].indexOf('&')>=0 && resultSet[counter].indexOf(';')>=0) {
value=value.replace(value.substring(resultSet[counter].indexOf('&'), resultSet[counter].indexOf(';')+1),'')
}
}
if (value)
{
value = value.trim();
if(HTMLParsedText === "")
{
HTMLParsedText = value;
}
else
{
if (value) {
HTMLParsedText = HTMLParsedText + "\n" + value;
}
}
value='';
}
counter= counter+1;
resultSetLength=resultSetLength-1;
}
console.log(HTMLParsedText);
其他回答
const getTextFromHtml = (t) =>
t
?.split('>')
?.map((i) => i.split('<')[0])
.filter((i) => !i.includes('=') && i.trim())
.join('');
const test = '<p>This <strong>one</strong> <em>time</em>,</p><br /><blockquote>I went to</blockquote><ul><li>band <a href="https://workingclasshistory.com" rel="noopener noreferrer" target="_blank">camp</a>…</li></ul><p>I edited this as a reviewer just to double check</p>'
getTextFromHtml(test)
// 'This onetime,I went toband camp…I edited this as a reviewer just to double check'
作为jQuery方法的扩展,如果字符串可能不包含HTML(例如,如果您试图从表单字段中删除HTML)
jQuery(html).text();
如果没有HTML,将返回空字符串
Use:
jQuery('<p>' + html + '</p>').text();
相反
更新:正如评论中所指出的,在某些情况下,如果攻击者可能影响html的值,则此解决方案将执行html中包含的javascript,请使用不同的解决方案。
如果你在浏览器中运行,那么最简单的方法就是让浏览器为你做。。。
function stripHtml(html)
{
let tmp = document.createElement("DIV");
tmp.innerHTML = html;
return tmp.textContent || tmp.innerText || "";
}
注意:正如人们在评论中所指出的,如果您不控制HTML的源代码(例如,不要在可能来自用户输入的任何内容上运行此代码),最好避免这种情况。对于这些场景,您仍然可以让浏览器为您完成工作-请参阅Saba关于使用现在广泛可用的DOMParser的回答。
这应该可以在任何Javascript环境(包括NodeJS)上完成工作。
const text = `
<html lang="en">
<head>
<style type="text/css">*{color:red}</style>
<script>alert('hello')</script>
</head>
<body><b>This is some text</b><br/><body>
</html>`;
// Remove style tags and content
text.replace(/<style[^>]*>.*<\/style>/gm, '')
// Remove script tags and content
.replace(/<script[^>]*>.*<\/script>/gm, '')
// Remove all opening, closing and orphan HTML tags
.replace(/<[^>]+>/gm, '')
// Remove leading spaces and repeated CR/LF
.replace(/([\r\n]+ +)+/gm, '');
对于转义字符,也可以使用模式匹配:
myString.replace(/((<)|(<)(?:.|\n)*?(>)|(>))/gm, '');