Examples (section header) (EN) - bhsd-harry/wikiparser-node GitHub Wiki

Other Languages

Renaming a section

Expand

You can rename a section from Reference to References in the content of a page. This example demonstrates the use of HeadingToken.

// Renaming a section (main)
// The content of a page containing a section named `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`,
);

Ordering sections

Expand

You can put the section named Notes before the section named References in the content of a page. This example demonstrates the use of Token.prototype.sections and AstRange.

// Ordering sections (main)
// The content of a page containing sections `Notes` and `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;
	// Must remove `notes` before inserting its children before `references`
	notes.remove();
	references.before(...childNodes);
}
assert.equal(
	root,
	`Foo

== Notes ==
Baz
== References ==
Bar

`,
);

Inserting TOC before the first section

Expand

You can insert the magic word __TOC__ before the first section. This example demonstrates the use of AstNode.prototype.before.

// Inserting TOC before the first section (main)
// The content of a page containing a section
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`,
);

Getting the URL fragment of a section

Expand

You can get the URL fragment of a section in the content of a page. This example demonstrates the use of HeadingToken.

// Getting the URL fragment of a section (main)
// The content of a page containing a section
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",
);
⚠️ **GitHub.com Fallback** ⚠️