微信小程序 处理富文本

处理富文本里的图片宽度自适应

  1. 去掉img标签里的style、width、height属性
  2. img标签添加style属性:max-width:100%;height:auto
  3. 修改所有style里的width属性为max-width:100%
  4. 去掉<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;
},

获取富文本里的真实内容 (不含标签、图片、空格、换行,然后将转义的特殊符号转回来)

  1. 去除标签、图片
  2. 去除空格
  3. 将转义的特殊符号转回来
formatRichText = (rich) => {
    
    
	// 对应替换的的内容
	const rep = {
    
    
		"&lsquo;": "‘",
		"&rsquo;": "’",
		"&ldquo;": "“",
		"&rdquo;": "”",
		"&hellip;": "…",
		"&middot;": "·",
		"&amp;": "&",
		"&lt;": "<",
		"&gt;": ">",
	}
	return 
		rich.replace(/<[^>]+>/g, "")
			.replaceAll(/\r|\n|\\s|&nbsp;|&ensp;|&emsp;/ig, "")
			.replaceAll(new RegExp(Object.keys(rep).join('|'),'ig'), function ($0) {
    
    
				return rep[$0];
			})
}

显示富文本

标签rich-text

<rich-text nodes="{
     
     {richText}}"></rich-text>

猜你喜欢

转载自blog.csdn.net/weixin_55556204/article/details/124488693