linkify
Install linkifyjs.
npm install linkifyjs --save
Covert link (with out without http://
) to HTML.
import linkifyHtml from 'linkifyjs/html'const str = 'Visit www.google.com or https://gohugo.io/hosting-and-deployment/hosting-on-github/, BYE!'const html = linkifyHtml(str, { className: 'link' })console.log(html)
Visit <a href="http://www.google.com" class="link" target="_blank">www.google.com</a> or <a href="https://gohugo.io/hosting-and-deployment/hosting-on-github/" class="link" target="_blank">https://gohugo.io/hosting-and-deployment/hosting-on-github/</a>, BYE!
Some link is too long https://gohugo.io/hosting-and-deployment/hosting-on-github/
, you might want to shorten it to https://gohugo.io/hosting-and-…
.
const str = 'Display shorter url: https://gohugo.io/hosting-and-deployment/hosting-on-github/, BYE!'const html = linkifyHtml(str, { className: 'link', format: (value, type) => { if (type === 'url' && value.length > 30) { value = value.slice(0, 30) + '…' } return value }})console.log(html)
Display shorter url: <a href="https://gohugo.io/hosting-and-deployment/hosting-on-github/" class="link" target="_blank">https://gohugo.io/hosting-and-…</a>, BYE!
twitter-text
twitter-text is capable of identifying and linking url, @username, #hastag and $cashtag.
Install.
npm install twitter-text --save
Code.
import twitterText from 'twitter-text'const str = 'Visit www.google.com or https://gohugo.io/hosting-and-deployment/hosting-on-github/, BYE!'const html = twitterText.autoLinkUrlsCustom(str)console.log(html)
Output.
Visit www.google.com or <a href="https://gohugo.io/hosting-and-deployment/hosting-on-github/" rel="nofollow">https://gohugo.io/hosting-and-deployment/hosting-on-github/</a>, BYE!
Note: auto link URL works for https://www.google.com
but not www.google.com
.