摘要
在一些快应用中,比如小程序中,可能会有需求,在输出的文章中,需要对图片可预览,正常的富文本内容是<img/>
标签,无法预览处理,因此需要将富文本中的图片路径和文本区分开发,以实现图片预览效果
代码
/* 对富文本进行分割 */
function sliceStr(str) {
let result = [];
// 提取url的正则
const reg = /<img.+?src=[\"\'](.+?)[\"\'].{0,}?>/g;
let index = 0;
// 针对p标签处理(浏览器端可能会有间隔,导致显示不一致)
// 加上类名,可以在css中处理
str = str.replace(/<p/g, '<p data-type="nodeText"')
str.replace(reg, (value, word, position) => {
const valueLen = value.length;
const text = {
type: 'text',
content: str.slice(index, position)
}
const img = {
type: 'image',
content: word
}
result.push(text, img);
index = position + valueLen;
})
result.push({
type: 'text',
content: str.slice(index)
})
return result
}
最终的结果是这种结构
const testStr=`<p>可靠消息,丧尸来袭</p>↵<p></p>↵<img src="http://test2.img.hiwemeet.com/pic/750-1624-607c0816fc41244429df1b658d4b22c7/0" alt="undefined" style="float:none;height: auto;width: auto"/>↵<p>大家快跑啊</p>`
console.log(trans(testStr))
原理
主要是利用了string的replace方法,第二个参数可以传递一个函数
函数的参数有
1.第一个参数是匹配到的字符串 如上就是
<img src="http://test2.img.hiwemeet.com/pic/750-1624-607c0816fc41244429df1b658d4b22c7/0" alt="undefined" style="float:none;height: auto;width: auto"/>
2.第二个参数是子表达式匹配的字符串 何谓子表达式?就是正则中括号中代表的内容,如果有多个括号的子表达式,那么这个参数可能有多个,这部分匹配到的内容就是对应的img中的src
http://test2.img.hiwemeet.com/pic/750-1624-607c0816fc41244429df1b658d4b22c7/0
3.第三个参数匹配到的字符串出现的位置,字符串的开始对应的index
4.第四个参数原始的字符串