前端,小程序通过view显示带 emoji 的复合文本

首先每个emoji 表情有保存到服务器,可以通过 URL 访问,如
http://…/em001

1.将带 emoji 标签复合文本字符串(如:你好,em001),分割成纯文本和 emoji 标签文本,并装进数组。方法如下
/**
根据说说内容,将文本、表情切分为数组
@param {string} content 说说源内容
*/
function messageContentArray (content) {
const reg = /[em[2-4]+\d{3}]/g;
const emRegArr = content.match(reg);
// 没有表情,直接返回文本内容
if (!emRegArr) return [{type: ‘text’, content}];

const indexArr = [];
const contentArr = [];
// 递增取得所有表情index
let pos = content.indexOf(emRegArr[0]);
for (let i = 1; i < emRegArr.length; i++) {
indexArr.push(pos);
pos = content.indexOf(emRegArr[i], pos + 1);
}
indexArr.push(pos);

indexArr.map((emIndex, i) => {
// 首个为表情
if (emIndex === 0) {
contentArr.push({type: ‘emotion’, source: emRegArr[i]});
} else {
if (i === 0) {
// TODO:临时的处理方式,待观察内存占用情况
for (let index = 0; index < emIndex; index++) {
contentArr.push({type: ‘text’, content: content[index]});
}
// contentArr.push({type: ‘text’, content: content.substr(0, emIndex)});
} else {
// 两个表情之间夹杂了文本
const preEmoLocation = indexArr[i - 1] + emRegArr[i - 1].length;
const locationDiff = emIndex - preEmoLocation;
if (locationDiff > 0) {
for (let index = preEmoLocation; index < locationDiff; index++) {
contentArr.push({type: ‘text’, content: content[index]});
}
// contentArr.push({type: ‘text’, content: content.substr(preEmoLocation, locationDiff)});
}
}
contentArr.push({type: ‘emotion’, source: emRegArr[i]});
}
});

const lastLocation = indexArr[indexArr.length - 1] + emRegArr[emRegArr.length - 1].length;
if (content.length > lastLocation) {
// contentArr.push({type: ‘text’, content: content.substr(lastLocation, content.length - lastLocation)});
for (let index = lastLocation; index < content.length; index++) {
contentArr.push({type: ‘text’, content: content[index]});
}
}

return contentArr;
}
2.然后在 view 标签,遍历数组

{contentArr.map((Citem, index) => {
if (Citem.type === ‘emotion’) {
const str = Citem.source.substr(1, Citem.source.length-2);
return <Image key={Emotion_${index}} className=“emoji” src={‘http://’+str+’.jpg’} />;
}
const isEnter = Citem.content === ‘\n’;
if (isEnter) {
// hack Text 显示单个 \n 时,会有样式问题
return <View key={Text_${index}} />;
}
return <Text key={Text_${index}} className=“txt” >{Citem.content};
})}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值