Files
johannes.gasser 57af0b8386
Build and Deploy / build-and-deploy (push) Successful in 2m53s
add skills
2026-05-18 08:39:42 +02:00

1.7 KiB

title, description, tags
title description tags
Extract Plain Text from Portable Text Convert Portable Text to plain text strings for search, meta descriptions, and summaries
portable-text
plain-text
search
seo
extraction

Extract Plain Text from Portable Text

Every @portabletext/* library exports a toPlainText() utility. Use it for meta descriptions, search indexing, summaries, and anywhere you need raw text without markup.

Usage

// From any framework library:
import {toPlainText} from '@portabletext/react'
// or: import {toPlainText} from '@portabletext/svelte'
// or: import {toPlainText} from '@portabletext/vue'
// or: import {toPlainText} from '@portabletext/to-html'

const plainText = toPlainText(portableTextBlocks)

Common Patterns

Meta Description

function getMetaDescription(body: PortableTextBlock[]): string {
  const text = toPlainText(body)
  return text.length > 160 ? text.slice(0, 157) + '...' : text
}

Search Indexing

// Index document content for search
const searchableText = toPlainText(document.body)

Slug Generation

import slugify from 'slugify'

const slug = slugify(toPlainText(blocks), {lower: true, strict: true})

Character/Word Count

const text = toPlainText(blocks)
const wordCount = text.split(/\s+/).filter(Boolean).length
const charCount = text.length

Behavior

  • Extracts text from all span children in block type nodes
  • Joins blocks with double newlines (\n\n)
  • Ignores custom block types (images, code blocks, etc.)
  • Strips all marks (bold, links, etc.) — returns raw text only

Reference