有没有一种简单的方法可以在JavaScript中获取一个html字符串并去掉html?
当前回答
如果您不想为此创建DOM(可能您不在浏览器上下文中),可以使用striptags npm包。
import striptags from 'striptags'; //ES6 <-- pick one
const striptags = require('striptags'); //ES5 <-- pick one
striptags('<p>An HTML string</p>');
其他回答
使用Jquery:
function stripTags() {
return $('<p></p>').html(textToEscape).text()
}
下面的代码允许您保留一些html标记,同时剥离所有其他标记
function strip_tags(input, allowed) {
allowed = (((allowed || '') + '')
.toLowerCase()
.match(/<[a-z][a-z0-9]*>/g) || [])
.join(''); // making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)
var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
return input.replace(commentsAndPhpTags, '')
.replace(tags, function($0, $1) {
return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
});
}
还可以使用出色的htmlparser2纯JSHTML解析器。这里是一个工作演示:
var htmlparser = require('htmlparser2');
var body = '<p><div>This is </div>a <span>simple </span> <img src="test"></img>example.</p>';
var result = [];
var parser = new htmlparser.Parser({
ontext: function(text){
result.push(text);
}
}, {decodeEntities: true});
parser.write(body);
parser.end();
result.join('');
输出将是这是一个简单的示例。
请在此处查看实际操作:https://tonicdev.com/jfahrenkrug/extract-text-from-html
如果您使用类似webpack的工具打包web应用程序,则这在节点和浏览器中都有效。
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'
我认为最简单的方法就是像上面提到的那样使用正则表达式。虽然没有理由使用一堆。尝试:
stringWithHTML = stringWithHTML.replace(/<\/?[a-z][a-z0-9]*[^<>]*>/ig, "");