Skip to content

Instantly share code, notes, and snippets.

@gagregrog
Created October 27, 2020 20:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gagregrog/c5eab610be5f8a5237c9c43e41bb65ca to your computer and use it in GitHub Desktop.
Save gagregrog/c5eab610be5f8a5237c9c43e41bb65ca to your computer and use it in GitHub Desktop.
Get plain text from nested DOM nodes
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