有没有一种简单的方法可以在JavaScript中获取一个html字符串并去掉html?
当前回答
const-htmlParser=new DOMParser().parseFromString(“<h6>用户<p>名称</p></h6>”,'text/html');const textString=htmlParser.body.textContent;console.log(textString)
其他回答
function stripHTML(my_string){
var charArr = my_string.split(''),
resultArr = [],
htmlZone = 0,
quoteZone = 0;
for( x=0; x < charArr.length; x++ ){
switch( charArr[x] + htmlZone + quoteZone ){
case "<00" : htmlZone = 1;break;
case ">10" : htmlZone = 0;resultArr.push(' ');break;
case '"10' : quoteZone = 1;break;
case "'10" : quoteZone = 2;break;
case '"11' :
case "'12" : quoteZone = 0;break;
default : if(!htmlZone){ resultArr.push(charArr[x]); }
}
}
return resultArr.join('');
}
在新创建的dom元素中说明>内部属性和<img oneror=“javascript”>。
用法:
clean_string = stripHTML("string with <html> in it")
演示:
https://jsfiddle.net/gaby_de_wilde/pqayphzd/
做可怕事情的顶级答案演示:
https://jsfiddle.net/gaby_de_wilde/6f0jymL6/1/
输入元素仅支持单行文本:
文本状态表示元素值的单行纯文本编辑控件。
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;
}
const strip=(text) =>{
return (new DOMParser()?.parseFromString(text,"text/html"))
?.body?.textContent
}
const value=document.getElementById("idOfEl").value
const cleanText=strip(value)
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);
一个非常好的库是净化html,它是一个纯JavaScript函数,可以在任何环境中使用。
我的案例是React Native,我需要从给定文本中删除所有HTML标记。所以我创建了这个包装函数:
import sanitizer from 'sanitize-html';
const textSanitizer = (textWithHTML: string): string =>
sanitizer(textWithHTML, {
allowedTags: [],
});
export default textSanitizer;
现在,通过使用textSanitizer,我可以获得纯文本内容。