extractText()
Extrait récursivement l'intégralité du contenu textuel d'un nœud HAST.
import { extractText } from "@unifast/core";Signature
function extractText(node: HastNode): stringParamètres
node
| Propriété | Type | Défaut | Description |
|---|---|---|---|
type | string | — | Le type de nœud ("root", "element", "text", etc.) |
children | HastNode[] | — | Nœuds enfants (pour les types "root" et "element") |
value | string | — | Contenu textuel (pour le type "text") |
Valeur de retour
string — L’ensemble du contenu textuel, concaténé depuis le nœud et ses descendants.
Utilisation
import { extractText } from "@unifast/core";
import type { HastElement } from "@unifast/core";
const element: HastElement = {
type: "element",
tagName: "p",
properties: {},
children: [
{ type: "text", value: "Hello " },
{
type: "element",
tagName: "strong",
properties: {},
children: [{ type: "text", value: "world" }],
},
],
};
const text = extractText(element);
console.log(text);
// Hello worldExemples
Extraire depuis un élément simple
import { extractText } from "@unifast/core";
import type { HastElement } from "@unifast/core";
const heading: HastElement = {
type: "element",
tagName: "h1",
properties: { id: "title" },
children: [{ type: "text", value: "Getting Started" }],
};
console.log(extractText(heading));
// Getting StartedExtraire depuis des éléments imbriqués
import { extractText } from "@unifast/core";
import type { HastElement } from "@unifast/core";
const paragraph: HastElement = {
type: "element",
tagName: "p",
properties: {},
children: [
{ type: "text", value: "This is " },
{
type: "element",
tagName: "em",
properties: {},
children: [
{ type: "text", value: "deeply " },
{
type: "element",
tagName: "strong",
properties: {},
children: [{ type: "text", value: "nested" }],
},
],
},
{ type: "text", value: " content." },
],
};
console.log(extractText(paragraph));
// This is deeply nested content.Élément vide
import { extractText } from "@unifast/core";
import type { HastElement } from "@unifast/core";
const emptyDiv: HastElement = {
type: "element",
tagName: "div",
properties: {},
children: [],
};
console.log(extractText(emptyDiv));
// (empty string)Génération de slugs de titres
import { extractText } from "@unifast/core";
import type { HastElement } from "@unifast/core";
const heading: HastElement = {
type: "element",
tagName: "h2",
properties: {},
children: [
{ type: "text", value: "API " },
{
type: "element",
tagName: "code",
properties: {},
children: [{ type: "text", value: "Reference" }],
},
],
};
const slug = extractText(heading).toLowerCase().replace(/\s+/g, "-");
console.log(slug);
// api-reference