有没有一种简单的方法可以在JavaScript中获取一个html字符串并去掉html?


当前回答

使用jQuery,您可以使用

$('#elementID').text()

其他回答

作为jQuery方法的扩展,如果字符串可能不包含HTML(例如,如果您试图从表单字段中删除HTML)

jQuery(html).text();

如果没有HTML,将返回空字符串

Use:

jQuery('<p>' + html + '</p>').text();

相反

更新:正如评论中所指出的,在某些情况下,如果攻击者可能影响html的值,则此解决方案将执行html中包含的javascript,请使用不同的解决方案。

方法1:

function cleanHTML(str){
  str.replace(/<(?<=<)(.*?)(?=>)>/g, '&lt;$1&gt;');
}

function uncleanHTML(str){
  str.replace(/&lt;(?<=&lt;)(.*?)(?=&gt;)&gt;/g, '<$1>');
}

方法2:

function cleanHTML(str){
  str.replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

function uncleanHTML(str){
  str.replace(/&lt;/g, '<').replace(/&gt;/g, '>');
}

此外,不要忘记,如果用户碰巧发布了一条数学评论(例如:1<2),您不想删除整个评论。浏览器(仅测试了chrome)不将unicode作为html标记运行。如果将所有<替换为&lt;字符串中的每一个文件,unicode都将显示<为文本,而不运行任何html。我推荐方法2。jquery也能很好地工作$('#element').text();

const strip=(text) =>{
    return (new DOMParser()?.parseFromString(text,"text/html"))
    ?.body?.textContent
}

const value=document.getElementById("idOfEl").value

const cleanText=strip(value)

要获得更简单的解决方案,请尝试此=>https://css-tricks.com/snippets/javascript/strip-html-tags-in-javascript/

var StrippedString = OriginalString.replace(/(<([^>]+)>)/ig,"");
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'