1

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 #

2 Answers 2

4
var text = "#sun#summer";
text.replace(/#([^\s#]+)/g, '<a href="/$1">#$1</a>');
# => "<a href="/sun">#sun</a><a href="/summer">#summer</a>"
Sign up to request clarification or add additional context in comments.

Comments

1

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>'

2 Comments

Thanks, It works for #sun#summer but not when there are other words in the text for example: hello #sun#summer sunny #hot, @falsetru's answer worked for all
here is another test string: hello #sun#summer sunny #hót #hot.hot, #hot_hot, #hot., can u help with this? hot.hot is valid, but hot. or hot, should only linkify hot , special char is also valid hót

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.