接口数据为html片段解决方法

项目场景:

PC端项目、vue技术栈


问题描述

接口数据字段为html片段,页面渲染只需要文字

![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/6e4d205331fdf8b0aae70ffb85f8b381.png#pic_center

原因分析:

数据内容可能是从其它的爬取,或者其他项目的页面片段内容


解决方案:

一般有三种解决方案
方案1:v-html指令
在内容区域使用v-html指令(v-html=“字段名称”)
缺陷:不安全,且无法编辑内容的样式

方案2:使用正则表达式
在页面内容区域添加文字样式有效,但是没办法把单独一段文字摘出来,只能添加整体的文字样式

const content = this.content
const regex = />([^<>]+)</g;
const regex2=/&nbsp;|&#160;/g    //摘掉$nbsp
const matches = content.matchAll(regex);
const textArray = [...matches].map((match) => match[1]);
this.text = textArray.join("").replace(/[\n\r\s]+/g, '').replace(regex2,'')
console.log(this.text); // "这是一段文字"
const content = this.content
const regex = />([^<>]+)</g;
const regex2=/&nbsp;|&#160;/g   //摘掉$nbsp
const matches = content.matchAll(regex);
const textArray = [...matches].map((match) => match[1]);
this.text = textArray.join("").replace(/[\n\r\s]+/g, '').replace(regex2,'')
console.log(this.text); // "这是一段文字"

方案3:使用第三方的插件
百度上有推荐,也可以解决问题,没有做具体尝试,现有项目没有具体用到。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值