简体   繁体   中英

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 #

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM