WikitextParser.js

WikitextParser.js is a standalone wikitext parser written in JavaScript. It's a collection of simple methods that build on each other to allow the extraction of almost any element from a given wikitext. It does not convert wikitext to HTML.

Usage

The source code is at MediaWiki:Gadget-Global-WikitextParser.js. You can load it remotely or copy-paste the source code into your project. It is hosted at MediaWiki.org so it can continue to be used on Wikimedia sites once the ban on third-party resources is enforced.

Examples

Getting the indexes

One thing WikitextParser.js doesn't do is return the indexes of each element. So if two elements (for example, two template calls) have exactly the same wikitext, you won't be able to distinguish them. To address this issue, here's a code pattern that will get you the indexes if you need them:

const templates = WikitextParser.getTemplates( wikitext );
let position = 0;
for ( const template of templates ) {
	const index = wikitext.indexOf( template, position );
	position = index + template.length;
}

See also