使用JavaScript在链接中包装多个主题标签 [英] Using JavaScript to wrap multiple hashtags in links

查看:95
本文介绍了使用JavaScript在链接中包装多个主题标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正用这个敲打我的头,经过几个小时的谷歌搜索,搜索Stack Exchange和反复试验我无法弄明白。任何帮助都将非常感激!

I'm banging my head against the wall with this, after a good few hours of Googling, searching Stack Exchange and trial and error I haven't been able to figure it out. Any help would be hugely appreciated!

我正在尝试用链接替换段落中的主题标签。我已经能够通过以下方式实现这一目标:

I'm trying to replace hashtags in a paragraphs with links. I've been able to do this by using the following:

var str = $('.item p').html(),
  regex = /(?:\s|^)(?:#(?!\d+(?:\s|$)))(\w+)(?=\s|$)/gi;

function replacer(){
  var replacementString = $.trim(str.match( regex )[0]);
  return ' <a href="https://www.example.com/'+ replacementString +'" target="_blank">' + replacementString + '</a>';
}
$('.item p').html( str.replace( regex , replacer ) );

这会成功替换主题标签,但是当我使用[0]时,如果有多个主题标签,那么它只用第一个的文本替换hashtag。这是我到目前为止的 JSFiddle 。我需要尝试弄清楚如何用指向特定主题标签的链接替换每个主题标签。

This replaces the hashtags successfully but as I'm using [0] then if there are multiple hashtags then it only replaces hashtag with the text of the first one. Here's a JSFiddle with what I have so far. I need to try to figure out how to replace each hashtag with a link to that particular hashtag.

我不确定我是否应该使用循环并递增[0]或者我是否在这里完全走错方向并且有更简单的方法来做到这一点。

I'm not sure whether I should be using a loop and incrementing the [0] or whether I'm going in completely the wrong direction here and there's an easier way to do this.

如果有人有任何指示而不是我真的很感激它!

If anyone has any pointers than I'd really appreciate it!

John

推荐答案

这样的简单改变函数将执行您想要的操作:

A simple change like this on your function will do what you want:

function replacer(hash){
  var replacementString = $.trim(hash);
  return ' <a href="https://www.example.com/'+ replacementString +'" target="_blank">' + replacementString + '</a>';
}

在这种情况下,无需在<$ c内进行匹配$ c> replacer 由 .replace 调用的函数,因为该函数的第一个参数已经是当前匹配的子字符串。

In you case, there's no need to do a match inside the replacer function invoked by .replace, as the first parameter of that function is already the current matched substring.

JSFiddle演示

JSFiddle Demo

编辑:如果你想匹配中间没有空格的主题标签,你可以稍微修改你的正则表达式:

If you want to match hashtags without spaces in between, you can modify your regex a little:

(?:|^)(?:#(?!\d+(?:\s|$)))(\w+)(?=\s|#|$)

更新的JSFiddle演示

UPDATED JSFiddle Demo

这篇关于使用JavaScript在链接中包装多个主题标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆