anchorify
v1.0.2
Published
Convert urls to anchor tags inside a string
Downloads
7,117
Maintainers
Readme
Anchorify
Convert all links inside a string to HTML anchor tags. It supports.
- URLs with(out) protocol.
- Detect email vs plain URLs.
- Adds
rel="noreferrer noopener"
as a security measure. - Normalizes urls without procotol or
www
. - Recognize existing anchor tags.
Installation
The code is hand-written in ES5 and is supposed to work with all major browsers. It makes use of var
over let or const
and for
over forEach
.
But you will need a commonjs module loader to make use of it.
npm i --save anchorify
Usage
const anchorify = require('anchorify')
assert.equal(
anchorify('Visit google.com'),
'Visit <a href="http://google.com"> google.com </a>'
)
// Set custom target
assert.equal(
anchorify('Visit google.com', { target: '_blank' }),
'Visit <a href="http://google.com" target="_blank" ref="noreferrer noopener"> google.com </a>'
)
// Do not touch existing anchor tags
assert.equal(
anchorify('Visit <a href="http://google.com"> google.com </a>', { target: '_blank' }),
'Visit <a href="http://google.com"> google.com </a>'
)
// Detect email
assert.equal(
anchorify('You can reach me at [email protected]'),
'You can reach me at <a href="mailto:[email protected]"> [email protected] </a>'
)
// Let browser decide the protocol
assert.equal(
anchorify('Open //google.com'),
'Open <a href="//google.com"> google.com </a>'
)