如果文本中的图片只有 <img src=""> 那么可以直接替换, 但是如果有其他的样式比如 width,height,style 时就需要先去掉其, 再替换
方法如下:
- /**
- * 处理富文本里的图片宽度自适应
- * 1. 去掉 img 标签里的 style,width,height 属性
- * 2.img 标签添加 style 属性: max-width:100%;height:auto
- * 3. 修改所有 style 里的 width 属性为 max-width:100%
- * 4. 去掉 <br/> 标签
- * @param html
- * @returns {void|string|*}
- */
- function formatRichText(HTML){
- let newContent= HTML.replace(/]*>/gi,function(match,capture){
- match = match.replace(/style="[^"]+"/gi,'').replace(/style='[^']+'/gi,'');
- 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, 'width:100%;').replace(/width:[^;]+;/gi, 'width:100%;');
- return match;
- });
- newContent = newContent.replace(/]*\/>/gi, '');
- newContent = newContent.replace(/\gi, ');
- return newContent;
- }
- // module.exports = {
- // formatRichText
- // }
- module.exports = {
- formatRichText: formatRichText
- }
来源: http://www.bubuko.com/infodetail-3516380.html