unified

Project: syntax-tree/hast-util-from-text

Package: hast-util-from-text@2.0.0

  1. Dependencies: 1·Dependents: 0
  2. hast utility to set the plain-text value of a node according to the innerText algorithm
  1. util 136
  2. utility 132
  3. unist 119
  4. html 111
  5. hast 61
  6. hast-util 40
  7. text 18
  8. content 18
  9. string 5
  10. innertext 2

hast-util-from-text

Build Coverage Downloads Size Sponsors Backers Chat

hast utility to get the plain-text value of a node.

This is like the DOMs Node#innerText setter.

You’d typically want to use hast-util-from-string (textContent), but hast-util-from-text (innerText) adds <br> elements instead of line breaks.

Install

This package is ESM only: Node 12+ is needed to use it and it must be imported instead of required.

npm:

npm install hast-util-from-text

Use

import {h} from 'hastscript'
import {fromText} from 'hast-util-from-text'

fromText(h('p'), 'Alpha')
// { type: 'element',
//   tagName: 'p',
//   properties: {},
//   children: [ { type: 'text', value: 'Alpha' } ] }

fromText(h('p', [h('b', 'Bravo'), '.']), 'Charlie')
// { type: 'element',
//   tagName: 'p',
//   properties: {},
//   children: [ { type: 'text', value: 'Charlie' } ] }

fromText(h('p'), 'Delta\nEcho')
// { type: 'element',
//   tagName: 'p',
//   properties: {},
//   children:
//    [ { type: 'text', value: 'Delta' },
//      { type: 'element', tagName: 'br', properties: {}, children: [] },
//      { type: 'text', value: 'Echo' } ] }

API

This package exports the following identifiers: fromText. There is no default export.

fromText(node[, value])

If the given node is a literal, set that to the given value or an empty string. If the given node is a parent, its children are replaced with new children: texts for every run of text and <br> elements for every line break (a line feed, \n; a carriage return, \r; or a carriage return + line feed, \r\n). If no value is given (empty string '', null, or undefined), the literal’s value is set to an empty string or the parent’s children are removed.

Security

Improper use can open you up to a cross-site scripting (XSS) attack as value is injected into the syntax tree. If operating on a <script> element, value will run in a browser.

Do not use user input in value when operating on script elements or use hast-util-santize.

Contribute

See contributing.md in syntax-tree/.github for ways to get started. See support.md for ways to get help.

This project has a code of conduct. By interacting with this repository, organization, or community you agree to abide by its terms.

License

MIT © Titus Wormer