这是后台返回的富文本数据格式,注意看里面有一个空的style="",首先需要把style=""字段删除掉,然后再用replace方法加上样式,否则会不生效
// 无style的写法
const regex = new RegExp('img','gi')
const str = htmlContent.replace(regex,`img style="max-width:100%;"`) // 加上自己所需要的样式
// 有style的写法
htmlContent = htmlContent.replace(/<img([\s\w"=\/\.:;]+)((?:(style="[^"]+")))/ig,'<img$1'); // 去除style
const regex = new RegExp('img','gi')
const str = htmlContent.replace(regex,`img style="max-width:100%;"`) // 加上自己所需要的样式
去除属性
repChar(e) {
const baseUrl = 'www.xxx.com/'; // 请求路径
e = e.replace(new RegExp('src="/', 'g'), 'src="' + baseUrl); // 给图片的 URL 地址加上请求路径
e = e.replace(/(style="(.*?)")|(class="(.*?)")|(width="(.*?)")|(height="(.*?)")/gi, ''); // 去除style、class、width、height属性
e = e.replace(/<img/gi, '<img style="width: 100%; height: auto" '); // 重置图片的宽高
e = e.replace(/ol|ul/gi, "p"); // 将 ol 与 ul 标签更换为 p 标签
}
富文本处理
// #ifdef MP || APP-PLUS
let info = uni.getSystemInfoSync();
var screenWidth = info.safeArea.width || info.screenWidth;
screenWidth += 'px';
// #endif
// #ifdef H5
var screenWidth = '100%';
// #endif
// 设置图片宽度
let rep = `<img style="width:100% !important;display:block;max-width: ${screenWidth} !important;"`;
var html = htmlContent.replace(/\\/g, '').replace(/<img/g, rep);
// 设置图片src
html = html.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, (match, capture) => {
return rep + ' src="' + capture + '"/>';
});
// 去掉doctype
html.replace(/<\?xml.*\?>\n/, '').replace(/<!doctype.*>\n/, '').replace(/<!DOCTYPE.*>\n/, '');
// 去掉注释
html.replace(/<!--[\s\S]*-->/gi, '');
// 双引号改为单引号
html.replace(/style\s*=\s*["][^>]*;[^"]?/gi, (match, capture) => {
match = match.replace(/[:](\s?)[\s\S]*/gi, (a, b) => {
return a.replace(/"/g, "'");
});
return match;
});
return html;
参考链接:blog.csdn.net/Dream_Fever…