jQuery实现字符串中#前缀词汇替换为可点击超链接的方法
实现方案
你不需要单独先提取所有带#的词汇,直接用正则全局替换即可,代码如下:
单个评论字符串替换方法
function replaceHashToLink(comment) { // 正则匹配所有#开头的单词,捕获#后的内容 return comment.replace(/#(\w+)/g, (match, hashText) => { return `<a href="https://www.google.com?hashtag=${encodeURIComponent(hashText)}" rel="nofollow noreferrer">${match}</a>` }) } // 调用示例 const comment1 = "I am a #smart person." console.log(replaceHashToLink(comment1)) // 输出:I am a <a href="https://www.google.com?hashtag=smart" rel="nofollow noreferrer">#smart</a> person.
批量替换页面中所有评论的jQuery代码
如果你的评论已经渲染在页面的p标签中,直接运行以下代码即可完成替换:
$('p').each(function() { // 拿到原文本内容 const originalContent = $(this).text() // 替换hashtag为链接 const newContent = originalContent.replace(/#(\w+)/g, (match, hashText) => { return `<a href="https://www.google.com?hashtag=${encodeURIComponent(hashText)}" rel="nofollow noreferrer">${match}</a>` }) // 替换原标签内容 $(this).html(newContent) })
注意事项
- 如果你需要支持中文、特殊符号等非英文hashtag,可以把正则
/#(\w+)/g替换为/#([^\s]+)/g,该规则会匹配#之后到空格前的所有字符 encodeURIComponent用于转义hashtag中的特殊字符,避免生成的链接出现格式错误- 替换后必须用
html()方法写入内容,不能用text(),否则a标签会被当作纯文本展示
内容的提问来源于stack exchange,提问作者Karthik
相关产品推荐
相关产品推荐

