Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - Find Hashtags in Text and Return With Link

I'm trying to take my text and convert that hashtags to links and different colors than the normal text, but I have no idea how to go about it. I know it has something to do with regex, but I can't seem to get it down. Here's what I have so far, but it doesn't work at all:

function hashtag(text) {
var repl = text.replace(/(^|\W)(#[a-z\d][\w-]*)/ig, '$1<a style = "color: #35ab52">$2</a>');
return(repl);
}

I'd appreciate any help, thanks!

like image 868
Collin Avatar asked Jul 01 '16 14:07

Collin


1 Answers

Here is a simple function that replace all #string in a text with <a href="#">#string</a> :

function hashtag(text){
    var repl = text.replace(/#(\w+)/g, '<a href="#">#$1</a>');
    return repl;
}
like image 110
baronearl Avatar answered Sep 30 '22 11:09

baronearl