Created
October 27, 2020 20:10
-
-
Save gagregrog/c5eab610be5f8a5237c9c43e41bb65ca to your computer and use it in GitHub Desktop.
Get plain text from nested DOM nodes
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
function getText(node) { | |
const getTextRecursively = (currentNode) => { | |
const { type, data, children } = currentNode; | |
if (type === 'text') { | |
return data.replace(/ /g, '').replace(/\n/g, ''); | |
} else if (type === 'tag' && children) { | |
let childrenText = ''; | |
children.forEach(child => { | |
childrenText += getTextRecursively(child); | |
}); | |
return childrenText; | |
} else return ''; | |
}; | |
return getTextRecursively(node); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment