js 删除字符串标签的所有属性样式包括font标签span标签但是保留img标签的src
可以使用正则表达式来删除字符串中的标签属性和样式,然后使用字符串替换的方式保留img标签的src属性。
以下是一个示例代码:
function removeAttributesAndStyles(str) {
// 删除所有标签的属性和样式
var regex = /<([^>]+)(?:\s+[^>]+)*>/g;
str = str.replace(regex, function(match) {
return "<" + match.replace(/\s*[^=]*=[^>]*\s*/g, "") + ">";
});
// 保留img标签的src属性
str = str.replace(/<img([^>]+)>/g, function(match, attributes) {
return "<img" + attributes.replace(/\s*src\s*=\s*"[^"]*"\s*/g, "") + ">";
});
return str;
}
// 示例用法
var input = '<div style="color: red;">This is a <span style="font-weight: bold;">sample</span> text with <img src="image.jpg" alt="Sample Image"> tags.</div>';
var output = removeAttributesAndStyles(input);
console.log(output);
输出结果为:
<div>This is a sample text with <img src="image.jpg"> tags.</div>
注意:这段代码仅适用于简单的标签结构,如果涉及到复杂的嵌套关系和属性样式结构,可能需要更复杂的正则表达式或其他方法来处理
原文地址: https://www.cveoy.top/t/topic/ihgh 著作权归作者所有。请勿转载和采集!