Convert Sanity rich text to plain text string
Great to hear you're loving Sanity! Yes, you can absolutely convert Portable Text to plain text strings, similar to Prismic's $prismic.asText(). There are several ways to do this:
1. Using pt::text() in GROQ queries (Recommended)
The most efficient approach is using the built-in pt::text() GROQ function directly in your queries:
*[_type == "post"] {
title,
"description": pt::text(body)
}This converts your Portable Text field to plain text at query time, which is perfect for generating excerpts, meta descriptions, or search indexing.
2. Using JavaScript/TypeScript packages
For client-side conversion, you have a few npm package options:
- @portabletext/toolkit - The modern, official package with a
toPlainTextfunction - @sanity/block-content-to-plain-text - The older package (still works)
Example usage:
import {toPlainText} from '@portabletext/toolkit'
const plainText = toPlainText(portableTextBlocks)3. Simple custom function
If you want a lightweight solution without dependencies, here's a simple function from the Sanity docs:
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')
}This traverses the Portable Text block structure and extracts just the text content, joining paragraphs with double line breaks.
Which approach to use?
- Use
pt::text()in GROQ if you're querying data and want plain text in your API response - Use
@portabletext/toolkitif you need to convert Portable Text on the client side - Use the custom function if you want zero dependencies and a simple solution
All of these will give you functionality equivalent to Prismic's asText() method!
Show original thread2 replies
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.