Jump to content

User:Ahecht/Scripts/refrescue.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
/******************************************************************************/
/* This script is designed to run from the browser console ([[HELP:CONSOLE]]) */
/* on both pages with errors about missing references and on the page where   */
/* the references can be found.                                               */
/*                                                                            */
/* This script is particularly useful when splitting pages that use named     */
/* named references. getNames() is run on the new page created after the      */
/* split, and getRefs() is run on the source page (in edit mode). The list of */
/* references produced by getRefs() can be inserted into the new page as      */
/* [[Help:List-defined references]].                                          */
/******************************************************************************/

// Run from the console on the page with missing reference errors
function getNames() {
	const errorSpans = document.querySelectorAll('span.mw-ext-cite-error');
	const refNames = [];
	errorSpans.forEach(span => {
		const codeTag = span.querySelector('code');
		if (codeTag) {
			const refName = codeTag.textContent.trim();
			if (refName) {
				refNames.push(refName);
			}
		}
	});
	console.log(refNames.join());
}

// Edit the page that has the references you need and run the following script
// in the console with the text editor window visible. You can pre-load the
// list of names with var refNames = 'comma,separated,list,of,names';
function getRefs() {
	if (!refNames) {
		const refNames = prompt('Please enter a comma-separated list of names:');
	}
	
	const refs = [];
	const notFound = [];
	const names = refNames.split(',').map(name => name.trim());
	const textareaContent = document.getElementById('wpTextbox1').value;
	const refRegex = /<ref name\s*=\s*['"]?([^'"\/>]+)['"]?\s*>(.*?)<\/ref>/gim;

	names.forEach(name => {
		let found = false;
		let match;
		while ((match = refRegex.exec(textareaContent)) !== null) {
			if (match[1] == name) {
				refs.push(match[0]);
				found = true;
				break;
			}
		}
		if (found === false) {notFound.push(name)}
	});
	console.log(refs.join('\n'));
	if (notFound.length > 0) {
		console.log("The following references were not found:", notFound.join());
	}
}