unified

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

Package:hast-util-from-text@1.0.2

  1. Dependencies:0·Dependents:0
  2. hast utility to set the plain-text value of a node according to the innerText algorithm
  1. util 105
  2. utility 105
  3. html 100
  4. unist 90
  5. hast 51
  6. hast-util 40
  7. text 13
  8. content 9
  9. string 4
  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

npm:

npm install hast-util-from-text

Use

var h = require('hastscript')
var fromText = require('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

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