MediaWiki:Gadget-BC-AD.js

Note – after saving, you may have to bypass your browser’s cache to see the changes.

  • Mozilla / Firefox / Safari: hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (Command-R on a Macintosh);
  • Konqueror and Chrome: click Reload or press F5;
  • Opera: clear the cache in Tools → Preferences;
  • Internet Explorer: hold Ctrl while clicking Refresh, or press Ctrl-F5.

// <nowiki>
// Switches the year-numbering system from BCE/CE to BC/AD
/* jshint undef: true */
/* globals $, mw */
"use strict";

function yearFormatSwitch() {
	/*
	 * This code supports date labels formatted using the following wikitext.
	 * (See {{B.C.E}} and {{C.E.}}.) BCE can be replaced by CE:
	     <small class="ce-date">[[Appendix:Glossary#BCE|<span title="Glossary and display preference">BCE</span>]]</small>
	 */
	var convert = { "BCE": "BC", "B.C.E.": "B.C.", "CE": "AD", "C.E.": "A.D." };
	var datetags = document.getElementsByClassName("ce-date");
	var articlePath = mw.config.get("wgArticlePath");
	var links = {
		BC: articlePath.replace("$1", "Appendix:Glossary#BC"),
		AD: articlePath.replace("$1", "Appendix:Glossary#AD")
	};
	
	for (var i = 0; i < datetags.length; i++) {
		var datetag = datetags[i],
			link = datetag && datetag.firstChild,
			innerSpan = link && link.firstChild,
			abbreviation = innerSpan && innerSpan.firstChild && innerSpan.firstChild.nodeValue;
		if (!(link && innerSpan && abbreviation))
			continue;
		if (abbreviation === "CE" || abbreviation === "C.E.") {
			link.href = links.AD;
			innerSpan.textContent = convert[abbreviation];
			
			// Change position of year number: 10 CE → AD 10.
			var beforeDatetag = datetag.previousSibling;
			if (!beforeDatetag)
				continue;
			var patt = /((?:\d{1,4}\s*(?:-|–|to)\s*)?\d{1,4})\s*$/; // first if hyphen-minus, then en-dash
			var matches = beforeDatetag.nodeValue.match(patt);
			if (matches === null)
				continue;
			var yearNumber = matches[matches.length - 1];
			beforeDatetag.nodeValue = beforeDatetag.nodeValue.substring(0, beforeDatetag.nodeValue.length - matches[0].length);
			datetag.parentElement.insertBefore(document.createTextNode(" " + yearNumber), datetag.nextSibling);
		} else if (abbreviation === "BCE" || abbreviation === "B.C.E.") {
			datetag.firstChild.href = links.BC;
			innerSpan.textContent = convert[abbreviation];
		}
	}
	
	/*
	 * This code handles dates with the class ce-date2:
	 *   <small class="ce-date2">CE</small>
	 */
	var datetags2 = document.getElementsByClassName("ce-date2");
	for (i = 0; i < datetags2.length; ++i ) {
		var datetag2 = datetags2[i];
		datetag2.textContent = convert[datetag2.textContent];
	}
}

$(yearFormatSwitch);

// </nowiki>