Join our next Developer Virtual Meetup – Live Q&A, Project Showcase, Swag raffle, and more πŸ”₯

Portable Text to Plain Text

By Espen Hovlandsdal

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


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 => child.text).join('')

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.


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