Welcome to the Ultimate Guide for LinkifyJS
LinkifyJS is a powerful JavaScript library designed to detect and convert links (URLs, email addresses, hashtags, mentions, etc.) in plain text to HTML <a> tags.
It makes it incredibly easy to automatically linkify your content without having to manually write HTML.
Features of LinkifyJS
- Convert URLs to clickable links
- Detect and linkify email addresses, hashtags, and mentions
- Customizable options and plugins for different use cases
- Easy-to-use API for complex link parsing tasks
Example APIs and Usage Scenarios
Basic Linkification
LinkifyJS can be used to linkify plain text strings easily with the following code:
const linkify = require('linkifyjs');
const html = linkify('Visit http://example.com for more info');
console.log(html);
// Output: 'Visit <a href="http://example.com">http://example.com</a> for more info'
Custom Link Types
You can also customize LinkifyJS to recognize other types of links, such as hashtags and mentions:
const linkifyHtml = require('linkifyjs/html');
const options = {
defaultProtocol: 'https',
formatHref: {
mention: (href) => 'https://twitter.com/' + href.substring(1)
}
};
const html = linkifyHtml('Tweet me @username', options);
console.log(html);
// Output: 'Tweet me <a href="https://twitter.com/username">@username</a>'
Using Plugins
LinkifyJS supports plugins to extend its capabilities. For instance, you can linkify hashtags:
const linkifyHtml = require('linkifyjs/html');
const hashtag = require('linkifyjs/plugins/hashtag');
hashtag(linkifyHtml);
const html = linkifyHtml('Check #awesome content!');
console.log(html);
// Output: 'Check <a href="https://twitter.com/hashtag/awesome">#awesome</a> content!'
Linkify in a Web Application
Here is an example of integrating LinkifyJS into a simple web application:
<!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/dist/linkify.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/linkifyjs/dist/linkify-html.min.js"></script>
</head>
<body>
<div id="content">Welcome to the website. Reach us at info@example.com</div>
<script>
document.addEventListener('DOMContentLoaded', () => {
const contentDiv = document.getElementById('content');
contentDiv.innerHTML = linkifyHtml(contentDiv.innerHTML);
});
</script>
</body>
</html>
By including the above code snippet in your HTML file, you can ensure that any plain text containing links, email addresses, and other elements gets converted to clickable links automatically.
Hash: f4489972bdc7b65ab64d4ac70ae07e13d6cdd85053d4fe2479212e20d5e2a487