How to convert the output of editorState to plain text? #1934
-
I am looking to convert the content in my editor to plain string file. Is this possible with any current plugins or utilities? So for example this:
Would be represented as:
|
Beta Was this translation helpful? Give feedback.
Replies: 5 comments 4 replies
-
I think import {
$getRoot,
} from 'lexical';
// ...
const stringifiedEditorState = JSON.stringify(
editor.getEditorState().toJSON(),
);
const parsedEditorState = editor.parseEditorState(stringifiedEditorState);
const editorStateTextString = parsedEditorState.read(() => $getRoot().getTextContent()) |
Beta Was this translation helpful? Give feedback.
-
I ended up doing this when my form is submitted:
In had to use |
Beta Was this translation helpful? Give feedback.
-
This worked for me: editor.getRootElement()?.textContent |
Beta Was this translation helpful? Give feedback.
-
This does not seem to include the text of HeadingNodes. Anyone knows how to include those? |
Beta Was this translation helpful? Give feedback.
-
In practice, it seems that the code given by the answer will add extra blank lines🧐? function editorStateToText(editor) {
const editorStateTextString = [];
const paragraphs = editor.getEditorState().toJSON().root.children;
paragraphs.forEach((paragraph) => {
const children = paragraph.children;
const paragraphText = [];
children.forEach((child) => {
if (child.type === 'linebreak') {
paragraphText.push('
');
} else if (child.text) {
paragraphText.push(child.text);
}
});
editorStateTextString.push(paragraphText.join(''));
});
return editorStateTextString.join('
');
} |
Beta Was this translation helpful? Give feedback.
I think
getTextContent
on the root node should produce what you need i.e.: