Examples (redirect) (EN) - bhsd-harry/wikiparser-node GitHub Wiki
Expand
Given a double redirect from Foo to Bar to Baz, you can fix it by editing the page Foo and changing the redirect target from Bar to Baz. This example demonstrates the use of Parser.redirects and RedirectTargetToken.
// Fixing double redirects (main)
import type {RedirectTargetToken} from "wikiparser-node";
Parser.redirects.set("Bar", "Baz");
// The content of the page `Foo`, which may contain extra wikitext
const content = `#REDIRECT [[Bar]]
{{Redirect category shell}}`,
root = Parser.parse(content, "Foo"),
target = root.querySelector<RedirectTargetToken>("redirect-target#Baz");
if (target?.innerText !== "Baz") {
target?.setTarget("Baz");
}
assert.equal(
root,
`#REDIRECT [[Baz]]
{{Redirect category shell}}`,
);Expand
Given a redirect from Foo to Bar, you can replace all links to Foo with links to Bar in the content of a page. This example demonstrates the use of Parser.redirects, LinkToken and Title.prototype.isRedirect.
// Replacing links to redirects (main)
import type {LinkToken} from "wikiparser-node";
Parser.redirects.set("Foo", "Bar");
// The content of a page containing links to `Foo`
const content = "[[Foo]] is a redirect to [[Foo|Bar]].",
root = Parser.parse(content);
for (const link of root.querySelectorAll<LinkToken>("link#Bar")) {
if (link.link.isRedirect()) {
// Preserve the link text, but change the target to `Bar`
link.setLinkText(link.innerText);
link.setTarget("Bar");
}
}
assert.equal(
root,
"[[Bar|Foo]] is a redirect to [[Bar|Bar]].",
);Expand
Given a redirect from Category:Foo to Category:Bar, you can fix category redirects in the content of a page by replacing category links to Category:Foo with category links to Category:Bar. This example demonstrates the use of Parser.redirects, CategoryToken and Title.prototype.isRedirect.
// Fixing category redirects (main)
import type {CategoryToken} from "wikiparser-node";
Parser.redirects.set("Category:Foo", "Category:Bar");
// The content of a page containing category links to `Category:Foo`
const content = `Foo is Bar.
[[Category:Foo]]`,
root = Parser.parse(content),
categories = root.querySelectorAll<CategoryToken>("category#Category:Bar");
for (const category of categories) {
if (category.link.isRedirect()) {
// Change the target to `Category:Bar`
category.setTarget("Category:Bar");
}
}
assert.equal(
root,
`Foo is Bar.
[[Category:Bar]]`,
);