Linkify URLs in a string
npm install linkify-urls> Linkify URLs in a string
``sh`
npm install linkify-urls
`js
import {linkifyUrlsToHtml, linkifyUrlsToDom} from 'linkify-urls';
linkifyUrlsToHtml('See https://sindresorhus.com', {
attributes: {
class: 'unicorn',
one: 1,
foo: true,
multiple: [
'a',
'b'
]
}
});
//=> 'See https://sindresorhus.com'
// In the browser
const fragment = linkifyUrlsToDom('See https://sindresorhus.com', {
attributes: {
class: 'unicorn',
}
});
document.body.appendChild(fragment);
`
Returns an HTML string like 'Visit https://example.com'.
#### string
Type: string
A string with URLs to linkify.
#### options
Type: object
##### attributes
Type: object
HTML attributes to add to the link.
Security note: For external links, consider adding rel: 'noreferrer' to prevent the linked page from accessing window.opener and to avoid sending referrer information. This helps protect against reverse tabnabbing attacks and preserves user privacy:
`js`
linkifyUrlsToHtml('Visit https://example.com', {
attributes: {
rel: 'noreferrer',
target: '_blank'
}
});
//=> 'Visit https://example.com'
##### value
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:
`js`
linkifyUrlsToHtml('See https://sindresorhus.com/foo', {
value: url => new URL(url).pathname
});
//=> 'See /foo'
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.
React component that linkifies URLs in its children.
`jsx
import React from 'react';
import {LinkifyUrls} from 'linkify-urls/react';
Check out https://example.com for more info.
`
This approach is safer and more performant than using dangerouslySetInnerHTML`.
#### options
See options above.
- linkify-issues - Linkify GitHub issue references
- get-urls - Get all URLs in a string