krisrak
krisrak

Reputation: 12952

linkify multiple hashtags with no space using javascript regex

I'm currently linkifying hashtags using regex like this:

var text = "#sun #summer";
text = text.replace(/(^|\s)#(\S+)/g, '$1<a href="/$2">#$2</a>');

output:

"#<a href="/sun">sun</a> #<a href="/summer">summer</a>"

this works fine, but sometimes people add hashtags without spaces in between them, so something like this: "#sun#summer"

how do I linkify this type of hashtags without spaces?

I tried this:

var text = "#sun#summer";
text = text.replace(/(^|.)#(.|\S+)/g, '$1<a href="/$2">#$2</a>');

output:

"<a href="/s">#s</a>un<a href="/s">#s</a>ummer"

but only works for one char after #

Upvotes: 1

Views: 621

Answers (2)

falsetru
falsetru

Reputation: 368984

var text = "#sun#summer";
text.replace(/#([^\s#]+)/g, '<a href="/$1">#$1</a>');
# => "<a href="/sun">#sun</a><a href="/summer">#summer</a>"

Upvotes: 4

Avinash Raj
Avinash Raj

Reputation: 174696

For the second one, you could try the below regex,

(^|\b)#([^#]+)

DEMO

Your code would be,

> var str = '#sun#summer';
> str.replace(/(^|\b)#([^#]+)/g, '$1<a href="/$2">#$2</a>');
'<a href="/sun">#sun</a><a href="/summer">#summer</a>'

Upvotes: 1

Related Questions