Jump to content

User:Alex 21/script-redlinks.js

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Alex 21 (talk | contribs) at 06:20, 29 February 2016. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
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.
$(function($) {
	var portletlink = mw.util.addPortletLink('p-tb', '#', 'Remove redlinks');
	$(portletlink).click( function(e) {
		e.preventDefault();
		var loc = window.location.href;
		var redlinks; var i;
		if (loc.indexOf('action=edit') < 0) {
			redlinks = [];
			var a = document.getElementsByTagName('a');
			for (i = 0; i < a.length; i++) {
				if (a[i].getAttribute('class') == "new") {
					redlinks[redlinks.length] = a[i].href.replace('https://en.wikipedia.org/w/index.php?title=','').replace('&action=edit&redlink=1','');
					while (redlinks[redlinks.length-1].indexOf('_')>=0) redlinks[redlinks.length-1] = redlinks[redlinks.length-1].replace('_',' ');
					redlinks[redlinks.length-1] = decodeURIComponent(redlinks[redlinks.length-1]);
				}
			}
			if (redlinks.length > 0) {
				localStorage.redlinks = JSON.stringify(redlinks);
				alert('You will need to click this link again after the editing page loads to remove the redlinks.');
				window.location = window.location.href.substr(0, window.location.href.indexOf('#'))+"?action=edit";
			} else {
				alert('No redlinks!');
			}
		} else {
			var totalredlinks = 0;
			RegExp.quote = function(str) { return str.replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&"); };

			redlinks = JSON.parse(localStorage.redlinks);
			var wpTextbox1 = document.getElementById('wpTextbox1');
			for (i = 0; i < redlinks.length; i++) {
				var reglink1 = new RegExp('\\[\\[('+RegExp.quote(redlinks[i])+')\\|([^\\]]*)\\]\\]','gi');
				var reglink2 = new RegExp('\\[\\[('+RegExp.quote(redlinks[i])+')\\]\\]','gi');
				if (wpTextbox1.value.match(reglink1) !== null) totalredlinks += wpTextbox1.value.match(reglink1).length;
				if (wpTextbox1.value.match(reglink2) !== null) totalredlinks += wpTextbox1.value.match(reglink2).length;
				wpTextbox1.value = wpTextbox1.value.replace(reglink1,"$2");
				wpTextbox1.value = wpTextbox1.value.replace(reglink2,"$1");
			}

			if (totalredlinks > 0) document.getElementById('wpSummary').value = "Removed "+totalredlinks+" redlink"+(totalredlinks==1?"":"s")+" via [[User:AlexTheWhovian/Scripts#Removing redlinks|script]].";
			else alert('No redlinks! (Check the navigational boxes.)');
		}
	});
});