Structured Content 2022: Join our conference to explore fresh perspectives on content and digital experiences →

Portable Text to Plain Text

By Espen Hovlandsdal

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

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

Other schemas by author

Auto-reload Studio when changes are deployed

Drop this into your Studio to let editors know when there's a more recent version of your Studio available, making sure they have the latest fields and validations.

Go to Auto-reload Studio when changes are deployed