extractLang()

Извлекает язык программирования из className элемента code.

import { extractLang } from "@unifast/core";

Сигнатура

function extractLang(code: HastElement): string | null

Параметры

code

СвойствоТипПо умолчаниюОписание
type"element"Идентификатор типа узла
tagNamestringИмя HTML-тега (обычно "code")
propertiesRecord<string, unknown>Свойства элемента, включая className
childrenHastNode[]Дочерние узлы элемента

Возвращаемое значение

string | null — идентификатор языка, извлечённый из первого класса language-*, либо null, если класс языка не найден.

Использование

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);
// typescript

Примеры

Извлечение языка из элемента code

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));
// js

Когда класс языка отсутствует

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));
// null

Когда className не массив

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));
// null

Использование совместно с 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
}