Linkify URLs in a string
npm install linkify-urls
import {linkifyUrlsToHtml, linkifyUrlsToDom} from 'linkify-urls';
linkifyUrlsToHtml('See https://sindresorhus.com', {
attributes: {
class: 'unicorn',
one: 1,
foo: true,
multiple: [
'a',
'b'
]
}
});
//=> 'See <a href="https://sindresorhus.com" class="unicorn" one="1" foo multiple="a b">https://sindresorhus.com</a>'
// In the browser
const fragment = linkifyUrlsToDom('See https://sindresorhus.com', {
attributes: {
class: 'unicorn',
}
});
document.body.appendChild(fragment);
Returns an HTML string like 'Visit <a href="https://example.com">https://example.com</a>'
.
Type: string
A string with URLs to linkify.
Type: object
Type: object
HTML attributes to add to the link.
Type: string | Function
Default: The URL
Set a custom HTML value for the link.
If it's a function, it will receive the URL as a string:
linkifyUrlsToHtml('See https://sindresorhus.com/foo', {
value: url => new URL(url).pathname
});
//=> 'See <a href="https://sindresorhus.com/foo">/foo</a>'
Returns a DocumentFragment
ready to be appended in a DOM safely, like DocumentFragment(TextNode('Visit '), HTMLAnchorElement('https://example.com'))
.
This type only works in the browser.
See options above.
Version 3 of this package uses negative lookbehind regex syntax. Stay on version 2 if you need to support browsers that doesn't support this feature.
- linkify-issues - Linkify GitHub issue references
- get-urls - Get all URLs in a string