markdown-section-parser
v0.0.4
Published
<!-- automd:badges color=yellow -->
Readme
markdown-section-parser
マークダウンテキストから見出し(h2〜h6)の構造を解析し、セクション情報を抽出するライブラリです。
機能
- マークダウンテキストから見出し(h2〜h6)を検出
- 見出しの階層構造を解析
- 自動的なセクション番号の生成(例:1、1-1、1-1-1)
- 各セクションの位置情報(オフセット)の計算
- 親子関係の特定
- コードブロック内のマークダウン構文を無視
- マークダウンの見出しをHTMLタグに変換
使用例
import { parseMarkdown } from 'markdown-section-parser';
const markdown = `## 環境構築
こちらでは、環境構築をやります。
### Node.jsの導入
nodejsをインストールしましょう。
#### 動作確認
\`node -v\`やってください。
### Dockerの導入
brewで入れましょう。`;
const sections = parseMarkdown(markdown);
console.log(sections);出力結果:
[
{
id: 1,
tag: "h2",
level: 2,
section: "1",
rawText: "## 環境構築",
line: 1,
column: 1,
offsetStart: 0,
offsetEnd: 7,
parentId: undefined
},
{
id: 2,
tag: "h3",
level: 3,
section: "1-1",
rawText: "### Node.jsの導入",
line: 4,
column: 1,
offsetStart: 26,
offsetEnd: 40,
parentId: 1
},
// ... 他のセクション
]インストール
# ✨ Auto-detect
npx nypm install markdown-section-parser
# npm
npm install markdown-section-parser
# yarn
yarn add markdown-section-parser
# pnpm
pnpm install markdown-section-parser
# bun
bun install markdown-section-parser
# deno
deno install markdown-section-parserAPI
parseMarkdown(markdown: string): MarkdownSection[]
マークダウンテキストを解析し、セクション情報の配列を返します。
戻り値の型定義
interface MarkdownSection {
id: number; // セクションの一意のID
tag: string; // HTMLタグ名(例:"h2", "h3")
level: number; // 見出しレベル(2〜6)
section: string; // セクション番号(例:"1", "1-1", "1-1-1")
rawText: string; // 元のマークダウンテキスト
line: number; // 行番号(1始まり)
column: number; // 列番号(常に1)
offsetStart: number; // テキスト内の開始位置
offsetEnd: number; // テキスト内の終了位置
parentId?: number; // 親セクションのID(なければundefined)
}convertMarkdownToHtml(markdown: string): string
マークダウンテキストの見出しをHTMLタグに変換します。セクション番号は data-section 属性として付与されます。
使用例
import { convertMarkdownToHtml } from 'markdown-section-parser';
const markdown = `## 挨拶
- これはテストテキストです。
### こんにちは
これもテストテキストです。`;
const html = convertMarkdownToHtml(markdown);
console.log(html);出力結果:
<h2 data-section="1">挨拶</h2>
- これはテストテキストです。
<h3 data-section="1-1">こんにちは</h3>
これもテストテキストです。convertSectionsToHtml(sections: MarkdownSection[], markdown: string): string
マークダウンセクション情報を元に、マークダウンテキストの見出しをHTMLタグに変換します。
その他のユーティリティ関数
splitLines(markdown: string): string[]- マークダウンテキストを行ごとに分割getHeaderLevel(line: string): number- 行の見出しレベルを取得(2〜6、見出しでない場合は0)isHeader(line: string): boolean- 行が見出し(h2〜h6)かどうかを判定isCodeBlockDelimiter(line: string): boolean- 行がコードブロックの区切り文字かどうかを判定
注意事項
- h1(
# 見出し)は対象外です - 見出しの判定には、
##の後にスペースが必要です(例:## 見出し) - コードブロック(```で囲まれた部分)内のマークダウン構文は解析対象外です
Development
- Clone this repository
- Install latest LTS version of Node.js
- Enable Corepack using
corepack enable - Install dependencies using
pnpm install - Run interactive tests using
pnpm dev
License
Published under the MIT license.
🤖 auto updated with automd
