JS code for processing rich text on mobile

Forget the source, there is an infringement contact. 
/**

* Process image width adaptation in rich text

* 1. Remove the style, width, and height attributes in the img tag

* 2. Add style attribute to img tag: max-width: 100%; height: auto

* 3. Modify the width attribute in all styles to max-width: 100%

* 4. Remove the <br/>tag

* @param html

* @returns {void|string|*}

*/

function formatRichText(html){

let newContent= html.replace(/<img[^>]*>/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, '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;margin-top:0;margin-bottom:0;"');

return newContent;

}

module.exports = {

formatRichText

}

Guess you like

Origin blog.csdn.net/qq_36338555/article/details/111316559