dbl-utils
Version:
Utilities for dbl, adba and others projects
38 lines (37 loc) • 1.28 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.extractNodeString = void 0;
const react_1 = __importDefault(require("react"));
/**
* Extracts all text nodes from a React element tree.
*
* @param obj - React node or primitive value to extract text from.
* @returns A string containing all text from the node tree.
*
* @example
* ```tsx
* const element = <div>Hello <span>World</span></div>;
* const text = extractNodeString(element);
* console.log(text); // "Hello World"
* ```
*/
const extractNodeString = (obj) => {
if (typeof obj === "string")
return obj;
if (Array.isArray(obj)) {
return obj.map(e => (0, exports.extractNodeString)(e)).filter(Boolean).flat().join(" ");
}
if (react_1.default.isValidElement(obj)) {
const node = obj;
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore - props may not exist for some nodes
return (0, exports.extractNodeString)(node.props.children);
}
if (!obj)
return "";
return obj.toString();
};
exports.extractNodeString = extractNodeString;