Search code examples
javascriptregexhashtaglinkify

linkify words using regex


I'm trying to linkify hashtags using regex, most of the cases work except when there is a word with dot at the end hot., this should only linkify #hot, but at the same time #hot.hot is valid

Here is my regex code:

var text = "#hot#hot hot #hot #hot.hot #hót #hot_hot #hot, (#hot) #hot. hot";
text.replace(#([^\b#,() ]*)/g, '<a href="/$1">#$1</a>');

output:

<a href="/hot">#hot</a><a href="/hot">#hot</a> hot <a href="/hot">#hot</a> <a href="/hot.hot">#hot.hot</a> <a href="/hót">#hót</a> <a href="/hot_hot">#hot_hot</a> <a href="/hot">#hot</a>, (<a href="/hot">#hot</a>) <a href="/hot.">#hot.</a> hot

the only issue is #hot. should linkify only #hot at the same time #hot.hot is valid


Solution

  • Your regex is fine, but you have to add a word boundary at the end:

    #([^\b#,() ]*)\b
                  ^-------- Here
    

    Working demo

    enter image description here