JavaScript Convert Link Text To Html

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.

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.