Convert Sanity rich text to plain text string

2 replies
Last updated: Apr 1, 2024
Sanity is for sure my favorite CMS ever, but one thing I really loved that I could leverage in prismic was turning rich text into plain text strings $prismic.asText(pageData.text) for instance. Is this something that is currently possible utilizing the sanity client?
AI Update

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:

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:

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/toolkit if 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 thread
2 replies
You can do this in groq: https://www.sanity.io/docs/groq-functions#1467558a0339

"content": pt::text(content)
user A
wow easy easy. thank you!

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.

Was this answer helpful?