微信小程序rich-text 文本首行缩进和图片居中和富文本rich-text 解析多个空格不成功 &nbsp

微信小程序开发使用rich-text组件渲染html格式的代码,常常因为不能自定义css导致文本不能缩进,以及图片不能居中等问题,这里可以考虑使用js的replace方法,替换字符串,然后在渲染的同时加载行内样式。

复制代码
//获取字符串的图片路径并替换
let content = res.data.articleVo.content
let re = /<img [^>]*src=['"]([^'"]+)[^>]*>/gi;
let srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i // 匹配图片中的src
let reHttp = new RegExp("http");
let imgArr = content.match(re);
for (let i = 0; i < imgArr.length; i++) {
  let imgSrc = imgArr[i].match(srcReg);
  if (!reHttp.test(imgSrc[1])) {
    content = content.replaceAll(imgSrc[1], URL.imghhx + imgSrc[1]);
  }
}
//先去掉本身的style
const regex = new RegExp('style="max-width:100%;" ', 'gi');
let contentIMg  = content.replace(regex, '');
//文本首行缩进和图片居中
let article = contentIMg.replace(/(\<img|\<p)/gi, function ($0, $1) {
  return {
    "<img": '<img style="width:100%;height:auto;display:block;" ',
    "<p": '<p style="text-indent: 24px;" ',
    "<article": "<div",
    "</article": "</div",
    "<header": "<div",
    "</header": "</div"
  } [$1];
});  

小程序富文本rich-text 解析多个空格不成功 &nbsp 解决方案

&nbsp; 替换为 &ensp;即可

复制代码
let str = '<p>&ensp; &ensp; 今天是阳光明媚的一天</p>'.replace(/&nbsp;/g, '&ensp;')
相关推荐
熬耶5 小时前
Uniapp之微信小程序自定义底部导航栏形态
微信小程序·小程序·uni-app
IT毕设实战小研8 小时前
基于Spring Boot校园二手交易平台系统设计与实现 二手交易系统 交易平台小程序
java·数据库·vue.js·spring boot·后端·小程序·课程设计
weixin_1772972206910 小时前
剧本杀小程序系统开发:重构推理娱乐生态
小程序·重构·娱乐
IT毕设实战小研1 天前
基于SpringBoot的救援物资管理系统 受灾应急物资管理系统 物资管理小程序
java·开发语言·vue.js·spring boot·小程序·毕业设计·课程设计
誰在花里胡哨1 天前
微信小程序实现陀螺仪卡片景深效果
前端·微信小程序·动效
XXXFIRE1 天前
微信小程序开发实战笔记:全流程梳理
前端·微信小程序
Thomas游戏开发1 天前
Cocos Creator 面试技巧分享
面试·微信小程序·cocos creator
小小愿望1 天前
微信小程序开发实战:图片转 Base64 全解析
前端·微信小程序
两个月菜鸟1 天前
vue+微信小程序五角星
vue.js·微信小程序·notepad++
Hashan1 天前
微信小程序:扁平化的无限级树
前端·微信小程序·uni-app