JS仿微信im文本消息超链接解析

511 阅读1分钟

介绍

当我们在做im即时聊天时,需要对用户发送的文本消息,进行处理,如果消息内容中包含链接的话,我们需要将其包装 成链接形式,点击可以跳转。 本文是参照微信消息解析链接的方式,大家可以收藏以方便日后使用。

效果预览

image.png

解析方法

/**
 * 解析文本消息
 * @param content {string} 文本内容
 * @return 解析后的消息 {html | string} 
 */
/**
 * 解析文本消息
 * @param content {string} 文本内容
 * @return 解析后的消息 {html | string} 
 */
function parseContent(content) {
  // 定义一个正则表达式,用于匹配链接部分或邮箱地址部分
  const LINK_REG = /((https?:\/\/)?([\da-z.,-]+)\.([a-z.,]{2,6})([/\w .,-]*)*(\?[\w%&=-]*)?(,\w+)*\.?)|([\w._%+-]+@[\da-z.-]+\.[a-z.]{2,6})/gi
  // 使用正则表达式匹配链接部分或邮箱地址部分,并去重
  const matchList = [...new Set(content.match(LINK_REG))]
  // 如果匹配成功,返回链接部分或邮箱地址部分和非链接部分,否则返回原数据
  if (matchList) {
    matchList.map((url) => {
      // 去除左右两边的空格、英文句号、英文逗号
      url = url.trim().replace(/^\.+|\.+$|^,+|,+$/g, '')
      // 链接如果不是http开头,则补上http
      const href = url.startsWith('http') ? url : `http://${url}`
      // 定义一个动态正则表达式全替换,英文问号需要转义
      const regex = new RegExp(url.replace('?', '\\?'), 'g')
      // 将链接改为a标签
      content = content.replace(regex, `<a href='${href}' target='_blank'>${url}</a>`)
    })
    return content
  } else {
    // 否则是纯文本,直接返回
    return content
  }
}