How to turn PortableText into plain text in Javascript?
Yes, there's a quick and easy way to convert Portable Text to plain text in JavaScript! You have several options depending on your needs:
Quick Plain Text Function
For a simple, no-dependencies solution, you can use this helper function that extracts just the text content:
function toPlainText(blocks = []) {
return blocks
.map(block => {
// If it's not a text block with children, return nothing
if (block._type !== 'block' || !block.children) {
return ''
}
// Loop through the children spans and join the text strings
return block.children.map(child => child.text).join('')
})
.join('\n\n')
}This traverses the top-level blocks in your Portable Text array and joins the text from all children, which is perfect for meta descriptions!
NPM Package Option
If you prefer an npm package, check out the @portabletext/toolkit package which includes a toPlainText utility function. There's also a community recipe for Portable Text to plain text on the Sanity website with the same approach.
Using with Your Gatsby Setup
Since you're already using block-content-to-react for rendering, you can add this plain text function alongside it. Just pass your Portable Text content through toPlainText() before setting it as your meta description:
const metaDescription = toPlainText(pageContent.body)The function handles non-text blocks gracefully by filtering them out, so you'll get clean plain text that's perfect for SEO meta tags.
Sanity – Build the way you think, not the way your CMS thinks
Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.