处理富文本里的图片宽度自适应
- 去掉
img
标签里的style、width、height属性
img
标签添加style属性:max-width:100%;height:auto
- 修改所有style里的width属性为max-width:100%
- 去掉
<br/>
标签
formatRichTextImg = (html) => {
let newContent= html.replace(/<img[^>]*>/gi,function(match,capture){
match = match.replace(/style="[^"]+"/gi, '').replace(/style\s*?=\s*?([‘"])[\s\S]*?\1/ig, '');
match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
return match;
});
newContent = newContent.replace(/style="[^"]+"/gi,function(match,capture){
match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
return match;
});
newContent = newContent.replace(/<br[^>]*\/>/gi, '');
newContent = newContent.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;"');
return newContent;
},
获取富文本里的真实内容 (不含标签、图片、空格、换行,然后将转义的特殊符号转回来)
- 去除标签、图片
- 去除空格
- 将转义的特殊符号转回来
formatRichText = (rich) => {
const rep = {
"‘": "‘",
"’": "’",
"“": "“",
"”": "”",
"…": "…",
"·": "·",
"&": "&",
"<": "<",
">": ">",
}
return
rich.replace(/<[^>]+>/g, "")
.replaceAll(/\r|\n|\\s| | | /ig, "")
.replaceAll(new RegExp(Object.keys(rep).join('|'),'ig'), function ($0) {
return rep[$0];
})
}
显示富文本
标签rich-text
<rich-text nodes="{
{richText}}"></rich-text>