rech-text.js 1.1 KB

12345678910111213141516171819202122232425262728
  1. /**
  2. * 处理富文本里的图片宽度自适应
  3. * 1.去掉img标签里的style、width、height属性
  4. * 2.img标签添加style属性:max-width:100%;height:auto
  5. * 3.修改所有style里的width属性为max-width:100%
  6. * 4.去掉<br/>标签
  7. * @param html
  8. * @returns {void|string|*}
  9. */
  10. function formatRichText(html){
  11. let newContent= html.replace(/<img[^>]*>/gi,function(match,capture){
  12. match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
  13. match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
  14. match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
  15. return match;
  16. });
  17. newContent = newContent.replace(/style="[^"]+"/gi,function(match,capture){
  18. match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
  19. return match;
  20. });
  21. newContent = newContent.replace(/<br[^>]*\/>/gi, '');
  22. newContent = newContent.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;margin-top:0;margin-bottom:0;"');
  23. return newContent;
  24. }
  25. module.exports = {
  26. formatRichText
  27. }