unified

Project: jaywcjlove/rehype-rewrite

Package: rehype-rewrite@1.0.2

  1. Dependencies: 0·Dependents: 0
  2. Rewrite element with rehype.
  1. unified 167
  2. markdown 135
  3. html 111
  4. rehype 78
  5. ast 31
  6. javascript 17
  7. rewrite 2

rehype-rewrite

NPM version Build Coverage Status

Rewrite element with rehype.

Installation

npm i rehype-rewrite
yarn add rehype-rewrite

Usage

const rehype = require('rehype')
const rehypeRewrite = require('rehype-rewrite')
const stringify = require('rehype-stringify')

const html = `<h1>header</h1>`;
const htmlStr = rehype()
  .data('settings', { fragment: true })
  .use(rehypeRewrite, (node, index, parent) => {
    if(node.type == 'text' && node.value == 'header') {
      node.value = ''
    }
  })
  .use(stringify)
  .processSync(html)
  .toString()
<h1>header</h1>

Output:

<h1></h1>
const rehype = require('rehype')
const rehypeRewrite = require('rehype-rewrite')
const stringify = require('rehype-stringify')

const html = `<h1>header</h1>`;
const htmlStr = rehype()
  .use(rehypeRewrite, (node) => {
    if (node.type == 'element' && node.tagName == 'body') {
      node.properties = { ...node.properties, style: 'color:red;'}
    }
  })
  .use(stringify)
  .processSync(html)
  .toString()
<h1>header</h1>

Output:

<html><head></head><body style="color:red;"><h1>header</h1></body></html>
const rehype = require('rehype')
const rehypeRewrite = require('rehype-rewrite')
const stringify = require('rehype-stringify')

const html = `<h1>hello</h1>`;
const htmlStr = rehype()
  .data('settings', { fragment: true })
  .use(rehypeRewrite, (node) => {
    if (node.type == 'element' && node.tagName == 'h1') {
      node.children = [ ...node.children, {
        type: 'element',
        tagName: 'span',
        properties: {},
        children: [
          {type: 'text', value: ' world'}
        ]
      }]
    }
  })
  .use(stringify)
  .processSync(html)
  .toString()
<h1>hello</h1>

Output:

<h1>hello<span> world</span></h1>
const unified = require("unified");
const remarkParse = require('remark-parse')
const remark2rehype = require('remark-rehype')
const rehypeRaw = require('rehype-raw')
const rehypeRewrite = require('rehype-rewrite')
const stringify = require('rehype-stringify')

const html = `<h1>hello</h1>`;
const htmlStr = unified()
  .use(remarkParse)
  .use(remark2rehype, { allowDangerousHtml: true })
  .use(rehypeRaw)
  .use(rehypeRewrite, (node) => {
    if (node.type == 'element' && node.tagName == 'p') {
      node.properties = { ...node.properties, style: 'color:red;' }
    }
  })
  .use(stringify)
  .processSync(html)
  .toString()
<h1>hello</h1>

Output:

<p style="color:red;">Hello World!</p>

License

MIT © Kenny Wong