Reputation: 12952
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
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
Reputation: 174696
For the second one, you could try the below regex,
(^|\b)#([^#]+)
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