admin管理员组

文章数量:1291470

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!

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!

Share asked Jul 1, 2016 at 14:49 CollinCollin 4971 gold badge6 silver badges18 bronze badges 4
  • What doesn't work about it? – Bubble Hacker Commented Jul 1, 2016 at 14:54
  • can you put together an example with data maybe on plunkr – terpinmd Commented Jul 1, 2016 at 15:01
  • 3 text.replace(/(#[^\s]*)/g, '<a style = "color: #35ab52">$1</a>'); – pishpish Commented Jul 1, 2016 at 15:15
  • Not working :/ Nothing happens – Collin Commented Jul 3, 2016 at 21:19
Add a ment  | 

1 Answer 1

Reset to default 11

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;
}

本文标签: htmlJavaScriptFind Hashtags in Text and Return With LinkStack Overflow