前端js实现正则表情包内容替换、前端表情包实现

欢迎点击关注-前端面试进阶指南:前端登顶之巅-最全面的前端知识点梳理总结

表情包实现

思路:通过全局正则针对文本内容走查,匹配到[嘿哈]文本表情包,通过创建div或者img标签,包裹将文本表情包替换成我们表情包的地址链接。

// 创建文件emoticon.js
import lottie from "lottie-web"; // 动画方法

const emoticon = new Map([
  ['[大笑]', {
    
    
    name: 'daxiao',
    src: 'https://url-daxiao.json' // 表情包地址
  }]
 ]}

// 根据资源文件生成正则匹配规则
const regExpFn = () => {
    
    
  let ruleStr = '';
  emoticon.forEach((val, key) => {
    
    
    const text = key.replace(/\[|\]/g, function (w: any): any {
    
    
      if (w === '[') {
    
    
        return '\\['
      } else if (w === ']') {
    
    
        return '\\]'
      }
    })
    ruleStr += text + '|'
  })
  ruleStr = ruleStr.substr(0, ruleStr.length - 1)
  return new RegExp(ruleStr, 'g')
}

// 替换内容里的表情包
const emotiomReplace = (params = {
     
     }) => {
    
    
  const lottieWrap = {
    
    };
  const {
    
     content, id } = params
  const result = content.replace(regExpFn(), (world, index) => {
    
    
    const type = world, lookId = id + '-' + index;
    if (lottieWrap[lookId]) return false;
      const div = document.getElementById(lookId)
      if (div && !div.innerHTML) {
    
    
        const path = emoticon.get(div.getAttribute('type')).src
        lottieWrap[lookId] = lottie.loadAnimation({
    
    
          container: div,
          renderer: 'svg',
          loop: true,
          path
        })
      }
    return `<div style="display: inline-block; width: 20px; height: 20px; 
    margin: 0 1px; vertical-align: middle;" type="${
      
      type}" id="${
      
      lookId}"></div>`
  })
  return result;
}

export {
    
    
  emotiomReplace
}
使用
import {
    
     emotiomReplace } from './emoticon.js'
<span v-html="emotiomReplace(后端数据)"></span>

猜你喜欢

转载自blog.csdn.net/weixin_43624724/article/details/120185799