Last active
June 3, 2023 00:58
-
-
Save jhlee8804/b9dfd8594f1400be3942f4facebe1f75 to your computer and use it in GitHub Desktop.
Get contenteditable plaintext with correct linebreaks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @see {@link https://stephenhaney.com/2020/get-contenteditable-plaintext-with-correct-linebreaks} | |
* @see {@link https://github.com/StephenHaney/stephenhaney/issues/6} | |
*/ | |
function parseValueFromContentEditable(e) { | |
let newValue = '' | |
let isOnFreshLine = true | |
function parseChildNodesForValueAndLines(childNodes) { | |
for (let i = 0; i < childNodes.length; i++) { | |
const childNode = childNodes[i] | |
if (childNode.nodeName === 'BR') { | |
// BRs are always line breaks which means the next loop is on a fresh line | |
newValue += '\n' | |
isOnFreshLine = true | |
continue | |
} | |
// We may or may not need to create a new line | |
if (childNode.nodeName === 'DIV' && isOnFreshLine === false) { | |
// Divs create new lines for themselves if they aren't already on one | |
newValue += '\n' | |
} | |
// Whether we created a new line or not, we'll use it for this content so the next loop will not be on a fresh line: | |
isOnFreshLine = false | |
// Add the text content if this is a text node: | |
if (childNode.nodeType === 3 && childNode.textContent) | |
newValue += childNode.textContent | |
// If this node has children, get into them as well: | |
parseChildNodesForValueAndLines(childNode.childNodes) | |
} | |
} | |
parseChildNodesForValueAndLines(e.currentTarget.childNodes) | |
return newValue | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment