前端获取富文本图片视频音频路径地址加接口前缀
前端从接口地址获取富文本内容,里面的图片/视频/音频路径地址需要我们自定义拼接接口地址前缀方法
从接口获取富文本字段直接调用方法
<mp-html :content="dealTxt(article.content)" @linktap="wxXcxFileDownLoad"/>
- 方法
dealTxt(htmlStr) {
console.log('htmlStr', htmlStr) // 从接口获取到富文本内容
let apiSource = this.risun.info.imgApi; // 地址端口
const _imgL = '<img src="';
const _video = '<video src="'
const _href = '<a href="'
if (htmlStr) {
// 解析富文本,获取所有图片标签或链接
const regex = /<img.*?src=["'](.*?)["']/g;
const images = [];
let match;
while ((match = regex.exec(htmlStr)) !== null) {
images.push(match[1]);
}
// 遍历每个图片链接,判断是否有前缀
for (const image of images) {
if (image.startsWith('http://') || image.startsWith('https://')) {
console.log(`${image} 包含前缀`);
} else {
console.log(`${image} 不包含前缀`);
// 给没有前缀的图片URL添加apiSource前缀
if (htmlStr.includes(_imgL)) {
htmlStr = htmlStr.replace(/<img src=\"/g,
'<img style="width:100%;height:auto" class="ui-iva" src="' + apiSource)
}
}
}
if (htmlStr.includes(_video)) {
htmlStr = htmlStr.replace(/<source src=\"/g, '<source src="ui-iva' + apiSource)
}
if (htmlStr.includes(_href)) {
htmlStr = htmlStr.replace(/<a href=\"/g, '<a href="' + apiSource)
}
}
return htmlStr;
}