前端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 `
${type}" id="${lookId}">
`
}) return result; } export { emotiomReplace }
使用
import { emotiomReplace } from './emoticon.js'
<span v-html="emotiomReplace(后端数据)"></span>

你可能感兴趣的:(工具类,vue,前端知识,javascript,html)