extractLang()
Extract the programming language from a code element's className.
import { extractLang } from "@unifast/core";Signature
function extractLang(code: HastElement): string | nullParameters
code
| Property | Type | Default | Description |
|---|---|---|---|
type | "element" | — | Node type identifier |
tagName | string | — | The HTML tag name (typically "code") |
properties | Record<string, unknown> | — | Element properties, including className |
children | HastNode[] | — | Child nodes of the element |
Returns
string | null — The language identifier extracted from the first language-* class, or null if no language class is found.
Usage
import { extractLang } from "@unifast/core";
import type { HastElement } from "@unifast/core";
const codeElement: HastElement = {
type: "element",
tagName: "code",
properties: { className: ["language-typescript"] },
children: [{ type: "text", value: "const x = 1;" }],
};
const lang = extractLang(codeElement);
console.log(lang);
// typescriptExamples
Extract language from a code element
import { extractLang } from "@unifast/core";
import type { HastElement } from "@unifast/core";
const code: HastElement = {
type: "element",
tagName: "code",
properties: { className: ["language-js", "highlight"] },
children: [{ type: "text", value: "console.log('hello');" }],
};
console.log(extractLang(code));
// jsWhen no language class exists
import { extractLang } from "@unifast/core";
import type { HastElement } from "@unifast/core";
const code: HastElement = {
type: "element",
tagName: "code",
properties: { className: ["highlight"] },
children: [{ type: "text", value: "plain text" }],
};
console.log(extractLang(code));
// nullWhen className is not an array
import { extractLang } from "@unifast/core";
import type { HastElement } from "@unifast/core";
const code: HastElement = {
type: "element",
tagName: "code",
properties: {},
children: [{ type: "text", value: "no classes" }],
};
console.log(extractLang(code));
// nullUsing with findCodeChild
import { extractLang, findCodeChild } from "@unifast/core";
import type { HastElement } from "@unifast/core";
const pre: HastElement = {
type: "element",
tagName: "pre",
properties: {},
children: [
{
type: "element",
tagName: "code",
properties: { className: ["language-python"] },
children: [{ type: "text", value: "print('hello')" }],
},
],
};
const code = findCodeChild(pre);
if (code) {
console.log(extractLang(code));
// python
}