Examples (external link) (EN) - bhsd-harry/wikiparser-node GitHub Wiki
Expand
You can replace http:// URLs from known domains with https:// URLs in the content of a page. This example demonstrates the use of MagicLinkToken.
// Replacing non-secure URLs with secure ones (main)
// The content of a page containing non-secure URLs
import type {MagicLinkToken} from "wikiparser-node";
const content = `http://www.mediawiki.org/wiki/Foo
[http://www.mediawiki.org/wiki/Bar Baz]`,
root = Parser.parse(content),
links = root.querySelectorAll<MagicLinkToken>(
"free-ext-link, ext-link-url",
);
for (const link of links) {
try {
// May throw if the URL is invalid
const url = link.getUrl() as URL;
if (url.host === "www.mediawiki.org" && url.protocol === "http:") {
link.protocol = "https://";
}
} catch {}
}
assert.equal(
root,
`https://www.mediawiki.org/wiki/Foo
[https://www.mediawiki.org/wiki/Bar Baz]`,
);Expand
You can replace bare URLs with citation templates in the content of a page. This example demonstrates the use of MagicLinkToken and ExtLinkToken.
// Replacing bare URLs with citation templates (main)
// The content of a page containing bare URLs
import type {ExtLinkToken, MagicLinkToken} from "wikiparser-node";
const content = `<ref>https://www.mediawiki.org/wiki/Foo</ref>
<ref>[https://www.mediawiki.org/wiki/Bar Baz]</ref>`,
root = Parser.parse(content),
links = root.querySelectorAll<ExtLinkToken | MagicLinkToken>(
"ext-inner#ref > ext-link, ext-inner#ref > free-ext-link",
);
for (const link of links) {
if (link.is<ExtLinkToken>("ext-link") && link.length === 2) {
link.replaceWith(`{{Cite web|url=${link.link}|title=${link.innerText}}}`);
} else {
link.replaceWith(`{{Cite web|url=${link.link}}}`);
}
}
assert.equal(
root,
`<ref>{{Cite web|url=https://www.mediawiki.org/wiki/Foo}}</ref>
<ref>{{Cite web|url=https://www.mediawiki.org/wiki/Bar|title=Baz}}</ref>`,
);Expand
You can replace deprecated ISBN magic links with templates in the content of a page. This example demonstrates the use of MagicLinkToken.
// Replacing ISBN magic links with templates (main)
// The content of a page containing ISBN magic links
import type {MagicLinkToken} from "wikiparser-node";
const content = "ISBN 1234567890",
root = Parser.parse(content),
isbns = root.querySelectorAll<MagicLinkToken>("magic-link[protocol=ISBN]");
for (const isbn of isbns) {
isbn.replaceWith(`{{ISBN|${isbn.link.slice(5)}}}`);
}
assert.equal(
root,
"{{ISBN|1234567890}}",
);