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