✨Discover storytelling in the AI age with Pixar's Matthew Luhn at Sanity Connect, May 8th—register now

How to turn PortableText into plain text in Javascript?

2 replies
Last updated: Dec 7, 2020
Hi! Is there a quick and dirty way to turn PortableText into plain text in JS? I have text for a Gatsby page that’s being transformed by “
user U
/block-content-to-react” which works really well; but it would be nice to just have a plain-text version of the page content that I could put in my meta descriptions. I’m guessing that someone must have solved this before more elegantly than I would? Thanks!
Dec 7, 2020, 1:58 AM
Hey Dan, you might find this useful, credit goes to Sanity team because I just pinched it from the portableText documentation, I use all the time for previews:

export default function toPlainText(blocks = []) {
  return blocks
    .map(block => {
      if (block._type !== 'block' || !block.children) {
        return ''
      }
      return block.children.map(child => child.text).join('')
    })
    .join('\n\n');
}
Dec 7, 2020, 7:53 AM
This works perfectly. Thanks.
Dec 7, 2020, 9:06 AM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?