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

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.io: Get the most out of your content

Sanity.io is a platform to build websites and applications. It comes with great APIs that let you treat content like data. Give your team exactly what they need to edit and publish their content with the customizable Sanity Studio. Get real-time collaboration out of the box. Sanity.io comes with a hosted datastore for JSON documents, query languages like GROQ and GraphQL, CDNs, on-demand asset transformations, presentation agnostic rich text, plugins, and much more.

Don't compromise on developer experience. Join thousands of developers and trusted companies and power your content with Sanity.io. Free to get started, pay-as-you-go on all plans.