Comprehensive Guide to linkifyjs Enhance Your Web Applications with Automatic Link Generation

Introduction to linkifyjs

linkifyjs is a versatile JavaScript library that automatically detects and converts plain text URLs, email addresses, hashtags, and mentions into interactive HTML links. It’s highly customizable and lightweight, making it an excellent choice for enhancing web applications. In this guide, we’ll explore its primary features and demonstrate various APIs with code snippets.

Basic Usage

You can include linkifyjs in your project by installing it via npm:


  npm install linkifyjs

Or by including it directly in your HTML:


  <script src="https://cdn.jsdelivr.net/npm/linkifyjs/dist/linkify.min.js"></script>

APIs and Code Snippets

Automatic Linkification

Automatically convert plain text links in a string:


  const linkify = require('linkifyjs');
  const inputText = 'Check out https://example.com and send email to test@example.com';
  const outputText = linkify.find(inputText);
  console.log(outputText);

Custom Linkifying

Customize the behavior of linkifying links:


  const inputText = 'Follow me on Twitter @example';
  const options = {
    formatHref: {
      mention: (href) => 'https://twitter.com' + href
    }
  };
  const outputHtml = linkifyHtml(inputText, options);
  console.log(outputHtml);

linkifyElement

Linkify all links in an HTML element:


  import linkifyElement from 'linkifyjs/element';
  const element = document.getElementById('content');
  linkifyElement(element);

linkifyHtml

Generate HTML with linkified links from a plain text:


  import linkifyHtml from 'linkifyjs/html';
  const html = linkifyHtml('Visit my site at www.example.com', { defaultProtocol: 'http' });
  console.log(html);

Adding Custom Schemes

Add new types of links:


  import linkify from 'linkifyjs';
  linkify.registerCustomProtocol('custom', (text) => 'custom://' + text);
  const outputHtml = linkifyHtml('custom://example');
  console.log(outputHtml);

Example Application

Consider a chat application that needs to detect links automatically. Here’s a simple implementation with linkifyjs:


  import linkifyHtml from 'linkifyjs/html';

  const messages = [
    'Hello visit http://example.com!',
    'Email me at contact@example.com'
  ];

  const linkifiedMessages = messages.map(message => linkifyHtml(message));

  function displayMessages(messages) {
    const container = document.getElementById('chat');
    messages.forEach(msg => {
      const p = document.createElement('p');
      p.innerHTML = msg;
      container.appendChild(p);
    });
  }

  displayMessages(linkifiedMessages);

With this implementation, the application will automatically convert URLs and email addresses into clickable links.

Hash: f4489972bdc7b65ab64d4ac70ae07e13d6cdd85053d4fe2479212e20d5e2a487

Leave a Reply

Your email address will not be published. Required fields are marked *