Linkifyjs – Automatically Detect and Convert URLs in Your Text
Linkifyjs is a powerful, flexible JavaScript library that automatically detects URLs, email addresses, and social media handles in plain text and converts them into clickable links. This can greatly improve user experience and SEO for your website.
Getting Started
To start using linkifyjs, you need to include it in your project. You can include it directly from a CDN:
<script src="https://cdn.jsdelivr.net/npm/linkifyjs@3.1.1/dist/linkify.min.js"></script>
Basic Usage
The basic usage of linkifyjs is straightforward. You just need to call the linkify
function on a string:
const linkified = linkify('Check out https://example.com and contact me at email@example.com!'); console.log(linkified); // Outputs: 'Check out https://example.com and contact me at email@example.com!'
Linkify Options
Linkifyjs provides several options to customize its behavior:
validate
– Enable or disable URL validation:
const linkified = linkify('http://invalid-url', { validate: false });
format
– Modify the displayed text of the links:const linkified = linkify('Visit https://example.com', { format: { url: (value) => 'my-website' } });
attributes
– Add custom attributes to generated links:const linkified = linkify('Go to https://example.com', { attributes: { rel: 'nofollow' } });
Advanced Customization
For more advanced customizations, you can use the linkify-html
or linkify-element
libraries:
const linkifyElement = require('linkifyjs/element'); linkifyElement(document.getElementById('content'), { validate: validateUrl, format: formatUrl, attributes: { target: '_blank' } });
For Node.js environments, you can use the linkify-string
library:
const linkify = require('linkifyjs/string'); const linkified = linkify('Check out https://example.com'); console.log(linkified);
Simple Web Application Example
Here’s a simple web application example that demonstrates the use of linkifyjs with both string and element methods:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Linkifyjs Example</title> <script src="https://cdn.jsdelivr.net/npm/linkifyjs@3.1.1/dist/linkify.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/linkifyjs@3.1.1/dist/linkify-element.min.js"></script> </head> <body> <h1>Linkifyjs Example</h1> <div id="content"> Check out https://example.com for more info. You can email me at email@example.com. </div> <script> const contentElement = document.getElementById('content'); linkifyElement(contentElement); </script> </body> </html>
Linkifyjs is straightforward to integrate into your projects and can significantly improve the user experience by automatically converting plain text URLs, email addresses, and other entities into clickable links.
Hash: f4489972bdc7b65ab64d4ac70ae07e13d6cdd85053d4fe2479212e20d5e2a487