Examples (section header) - bhsd-harry/wikiparser-node GitHub Wiki
展开
你可以将页面中的章节名从 Reference 重命名为 References。此示例演示了 HeadingToken 的用法。
// Renaming a section (main)
// 包含章节 `Reference` 的页面内容
import type {HeadingToken} from "wikiparser-node";
const content = `Foo
== Reference ==
Bar`,
root = Parser.parse(content);
for (const heading of root.querySelectorAll<HeadingToken>("heading")) {
if (heading.innerText === "Reference") {
heading.innerText = "References";
}
}
assert.equal(
root,
`Foo
==References==
Bar`,
);展开
你可以将页面中名为 Notes 的章节放在 References 章节之前。此示例演示了 Token.prototype.sections 和 AstRange 的用法。
// Ordering sections (main)
// 包含 `Notes` 和 `References` 章节的页面内容
import type {HeadingToken} from "wikiparser-node";
const content = `Foo
== References ==
Bar
== Notes ==
Baz`,
root = Parser.parse(content),
sections = root.sections()!,
references = sections.find(
section => section.querySelector<HeadingToken>("heading[level=2]")
?.innerText === "References",
),
notes = sections.find(
section => section.querySelector<HeadingToken>("heading[level=2]")
?.innerText === "Notes",
);
if (references && notes) {
const {childNodes} = notes;
// 必须先移除 `notes`,再将其子节点插入到 `references` 前
notes.remove();
references.before(...childNodes);
}
assert.equal(
root,
`Foo
== Notes ==
Baz
== References ==
Bar
`,
);展开
你可以在第一个章节前插入 魔术字 __TOC__。此示例演示了 AstNode.prototype.before 的用法。
// Inserting TOC before the first section (main)
// 包含章节的页面内容
import type {HeadingToken} from "wikiparser-node";
const content = `Foo
== Bar ==
Baz`,
root = Parser.parse(content),
heading = root.querySelector<HeadingToken>("heading");
if (heading) {
heading.before("__TOC__\n");
}
assert.equal(
root,
`Foo
__TOC__
== Bar ==
Baz`,
);展开
你可以获取页面中某个章节的片段标识符。此示例演示了 HeadingToken 的用法。
// Getting the URL fragment of a section (main)
// 包含章节的页面内容
import type {HeadingToken} from "wikiparser-node";
const content = `Foo
== <i>Bar</i> ==
Baz`,
root = Parser.parse(content),
heading = root.querySelector<HeadingToken>("heading"),
fragment = heading && `#${heading.id}`;
assert.equal(
fragment,
"#Bar",
);