What is @contentful/rich-text-plain-text-renderer?
@contentful/rich-text-plain-text-renderer is an npm package that provides functionality to convert Contentful's rich text documents into plain text. This can be useful for scenarios where you need to extract and manipulate text content without any formatting or HTML tags.
What are @contentful/rich-text-plain-text-renderer's main functionalities?
Convert Rich Text to Plain Text
This feature allows you to convert a Contentful rich text document into a plain text string. The code sample demonstrates how to use the `documentToPlainTextString` function to achieve this.
const { documentToPlainTextString } = require('@contentful/rich-text-plain-text-renderer');
const richTextDocument = {
nodeType: 'document',
content: [
{
nodeType: 'paragraph',
content: [
{
nodeType: 'text',
value: 'Hello, world!',
marks: [],
data: {}
}
],
data: {}
}
],
data: {}
};
const plainText = documentToPlainTextString(richTextDocument);
console.log(plainText); // Output: 'Hello, world!'
Other packages similar to @contentful/rich-text-plain-text-renderer
html-to-text
The `html-to-text` package converts HTML content into plain text. It is more general-purpose compared to @contentful/rich-text-plain-text-renderer, which is specifically designed for Contentful's rich text format. However, `html-to-text` can be used for a wider range of HTML content.
turndown
The `turndown` package is a highly customizable HTML to Markdown converter. While it focuses on converting HTML to Markdown, it can also be used to strip HTML tags and extract plain text. This makes it a versatile tool for text extraction, though it is not specifically tailored for Contentful's rich text format.
sanitize-html
The `sanitize-html` package is used to clean up and sanitize HTML content by removing unwanted tags and attributes. While its primary purpose is to sanitize HTML, it can also be configured to strip all tags, effectively converting HTML to plain text. This package offers more control over the sanitization process compared to @contentful/rich-text-plain-text-renderer.
rich-text-plain-text-renderer
Plain text renderer for the Rich Text document.
Installation
Using npm:
npm install @contentful/rich-text-plain-text-renderer
Using yarn:
yarn add @contentful/rich-text-plain-text-renderer
Usage
import { documentToPlainTextString } from '@contentful/rich-text-plain-text-renderer';
const document = {
nodeType: 'document',
data: {},
content: [
{
nodeType: 'paragraph',
data: {},
content: [
{
nodeType: 'text',
value: 'Hello',
marks: [{ type: 'bold' }],
data: {},
},
{
nodeType: 'text',
value: ' world!',
marks: [{ type: 'italic' }],
data: {},
},
],
},
],
};
documentToPlainTextString(document);