经过几个小时的谷歌搜索后,我正在用头撞击墙壁,搜索Stack Exchange并试错,我无法弄明白。 任何帮助将非常感谢!
我正在尝试用链接替换段落中的主题标签。 我已经能够通过使用以下内容来做到这一点:
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]时,如果有多个主题标签,那么它只用第一个标签替换主题标签。 这是我迄今为止所拥有的JSFiddle 。 我需要尝试弄清楚如何用指向该特定主题标签的链接替换每个主题标签。
我不确定我是否应该使用循环并递增[0]或者我是否在这里完全错误的方向,并且有更简单的方法来执行此操作。
如果有人有任何指针,我真的很感激!
约翰
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 ) );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.
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
最满意答案
在您的函数上进行这样的简单更改将执行您想要的操作:
function replacer(hash){ var replacementString = $.trim(hash); return ' <a href="https://www.example.com/'+ replacementString +'" target="_blank">' + replacementString + '</a>'; }在这种情况下,不需要在.replace调用的replacer函数内部进行匹配,因为该函数的第一个参数已经是当前匹配的子字符串。
JSFiddle演示
编辑:如果你想匹配中间没有空格的主题标签,你可以稍微修改你的正则表达式:
(?:|^)(?:#(?!\d+(?:\s|$)))(\w+)(?=\s|#|$)更新的JSFiddle演示
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>'; }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 Demo
EDIT: If you want to match hashtags without spaces in between, you can modify your regex a little:
(?:|^)(?:#(?!\d+(?:\s|$)))(\w+)(?=\s|#|$)UPDATED JSFiddle Demo
更多推荐
I'm,标签,主题,电脑培训,计算机培训,IT培训"/> <meta name="description&qu
发布评论