js 删除字符串标签的所有属性样式并且删除font标签span标签但是保留img标签的src
你可以使用正则表达式来删除字符串中的标签属性和特定的标签,同时保留img标签的src属性。
下面是一个示例代码:
function removeTags(str) {
// 删除所有标签的属性和样式
str = str.replace(/<[^>]+>/g, function(match) {
return match.replace(/(\w+)=["'][^"']*["']/g, '');
});
// 删除font和span标签
str = str.replace(/<(font|span)[^>]*>/g, '');
// 保留img标签的src属性
str = str.replace(/<img[^>]+src=["']([^"']+)["'][^>]*>/g, '<img src="$1">');
return str;
}
// 示例用法
var htmlString = '<div style="color: red;">This is a <font size="4">sample</font> <span style="font-weight: bold;">string</span> with an <img src="image.jpg" alt="image">.</div>';
var cleanedString = removeTags(htmlString);
console.log(cleanedString);
运行上述代码,输出结果将为:
This is a sample string with an <img src="image.jpg">.
其中,所有的标签属性和样式被删除,font和span标签被移除,但img标签的src属性被保留
原文地址: https://www.cveoy.top/t/topic/ihgl 著作权归作者所有。请勿转载和采集!