Joint session with Vercel: How to build intelligent storefronts (May 15th)

Portable Text to Plain Text

A small help function to convert Portable Text blocks to plain text

By Espen Hovlandsdal


portabletextToText.js

const defaults = {nonTextBehavior: 'remove'}

module.exports = function blocksToText(blocks, opts = {}) {
  const options = Object.assign({}, defaults, opts)
  return blocks
    .map(block => {
      if (block._type !== 'block' || !block.children) {
        return options.nonTextBehavior === 'remove' ? '' : `[${block._type} block]`
      }

      return block.children.map(child => child.text).join('')
    })
    .join('\n\n')
}

This function traverses the top-level blocks in a Portable Text array and joins the text property in its children. It also includes a pattern to deal with non-text blocks in a specific manner.

Contributor

Espen Hovlandsdal

Open-sourceror @ Sanity.io

United States

Visit Espen Hovlandsdal's profile