JavaScript Extract And Link Hashtag

December 18, 2017

twitter-text

Install twitter-text.

npm install twitter-text --save

Context hashtag to link (works for Chinese character as well).

import twitterText from 'twitter-text'

const str = 'I am #hello #My World #我爱你'

const html = twitterText.autoLinkHashtags(str, { hashtagUrlBase: '/tags/', hashtagClass: 'hashtag', suppressNoFollow: true })
console.log(html)

Output.

I am <a href="/tags/hello" title="#hello" class="hashtag">#hello</a> <a href="/tags/My" title="#My" class="hashtag">#My</a> World <a href="/tags/我爱你" title="#我爱你" class="hashtag">#我爱你</a>

twitter-text has a htmlEscape function as well.

const str = 'I am < #hello > <strong>not bold</string>'

let html = twitterText.htmlEscape(str)
console.log(html)

Output.

I am &lt; #hello &gt; &lt;strong&gt;not bold&lt;/string&gt;

Code.

html = twitterText.autoLinkHashtags(str , { hashtagUrlBase: '/tags/', hashtagClass: 'hashtag', suppressNoFollow: true })
console.log(html)

Output.

I am &lt; <a href="/tags/hello" title="#hello" class="hashtag">#hello</a> &gt; &lt;strong&gt;not bold&lt;/string&gt;

I am &lt;

twitter-text can extract and link url, hashtag and mention as well.

const str = 'I am #hashtag @mention https://www.google.com, BYE!'

const html = twitterText.autoLink(str)
console.log(html)
I am <a href="https://twitter.com/search?q=%23hashtag" title="#hashtag" class="tweet-url hashtag" rel="nofollow">#hashtag</a> @<a class="tweet-url username" href="https://twitter.com/mention" data-screen-name="mention" rel="nofollow">mention</a> <a href="https://www.google.com" rel="nofollow">https://www.google.com</a>, BYE!

Note: auto link URL works for https://www.google.com but not www.google.com.

linkify

linkifyjs has a hastag plugin as well.

npm install linkifyjs --save
import * as linkify from 'linkifyjs'
import linkifyHtml from 'linkifyjs/html'
import hashtag from 'linkifyjs/plugins/hashtag'

hashtag(linkify)

const str = 'I am #hello #My World #我爱你 www.google.com, BYE!'

const html = linkifyHtml(str, {
    nl2br: true, // optional
    formatHref: {
      hashtag: href => `/tags/${href.replace('#', '')}`
    },
    className: {
      hashtag: 'hashtag'
    }
  })

console.log(html)
I am <a href="/tags/hello" class="hashtag">#hello</a> <a href="/tags/My" class="hashtag">#My</a> World #我爱你 <a href="http://www.google.com" class="linkified" target="_blank">www.google.com</a>, BYE!

Note: hashtag doesn’t work for Chinese character

Note: url linking works for both https://www.google.com and www.google.com

Note: come with nl2br (convert newline \n to break <br>)

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.