How do I convert a string with new line character (\n) to Lexical state in JSON #4858
Unanswered
joaoguidev
asked this question in
Q&A
Replies: 1 comment
-
I've got this useEffect(() => {
editor.update(() => {
const root = $getRoot();
const splitted = textString.split(/\r?\n|\r|\n/g);
const paragraphNode = $createParagraphNode();
splitted.forEach((v) => {
// \n from the textString will become empty string array items
if (v.trim() === "") {
paragraphNode.append($createLineBreakNode());
paragraphNode.append($createLineBreakNode());
} else {
const textNode = $createTextNode(v);
paragraphNode.append(textNode);
}
});
root.append(paragraphNode);
});
}, [editor, textString]); |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Hello.
I want to covert a string that has \n characters into a lexical JSON state where the \n is taken in consideration.
Let's say that i have the string " I'm in the first line. \n I'm the in the second line. "
How do I parse it into a Lexical state in json format to end up with something like this:
{"editorState":{"root":{"children":[{"children":[{"detail":0,"format":0,"mode":"normal","style":"","text":"I'm in the first line.","type":"text","version":1}],"direction":"ltr","format":"","indent":0,"type":"paragraph","version":1},{"children":[{"detail":0,"format":0,"mode":"normal","style":"","text":"I'm in the second line.","type":"text","version":1}],"direction":"ltr","format":"","indent":0,"type":"paragraph","version":1}],"direction":"ltr","format":"","indent":0,"type":"root","version":1}},"lastSaved":1691084916260,"source":"Playground","version":"0.11.3"}
Observe that the \n in the playgroung is an paragraph node.
Or maybe there is an easier way of doing it.
I just want to be able to feed the editor with a string that has \n characters and I want the new line to be respected. The same way that would happen if i ctrl-c and ctrl-v the text from a word document.
Thank you
Beta Was this translation helpful? Give feedback.
All reactions