Skip to content

brechtcs/rehype-urls

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

9 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

rehype-urls

Rehype plugin to rewrite URLs of href and src attributes.

Installation

npm install rehype-urls

Usage

Given this markup:

<article>
  <img src="http://internal.site/image.jpg">
  <a href="http://internal.site/page.html">page</a>
  <a href="http://example.com">link</a>
</article>

You can use the following script:

var rehype = require('rehype')
var urls = require('rehype-urls')

rehype()
  .use(urls, removeBaseUrl)
  .process(input, handleOutput)

function removeBaseUrl (url) {
  if (url.host === 'internal.site') {
    return url.path
  }
}

Which will transform it into:

<article>
  <img src="/image.jpg">
  <a href="/page.html">page</a>
  <a href="http://example.com">link</a>
</article>

You can also pass in an object:

rehype()
  .use(urls, { transform: removeBaseUrl })
  .process(input, handleOutput)

Mutate nodes

It's also possible to mutate the URL nodes directly. This example will add target="_blank" to any external links:

var rehype = require('rehype')
var urls = require('rehype-urls')

rehype()
  .use(urls, blankExternal)
  .process(input, handleOutput)

function blankExternal (url, node) {
  if (url.host !== 'internal.site') {
    node.properties.target = '_blank'
  }
}

License

Apache-2.0

About

Rehype plugin to rewrite URLs

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 3

  •  
  •  
  •