Jump to content

User:Polygnotus/typo.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.
// https://en.wikipedia.org/w/index.php?title=Giraffe&action=edit&typo=the&typofix=teh

// <nowiki>
$(document).ready(function() {
    function getUrlParameter(name) {
        name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
        var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
        var results = regex.exec(location.search);
        return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
    }

    function replaceTextInWikitextEditor(typo, typofix) {
        var editTextarea = document.getElementById('wpTextbox1');
        if (editTextarea) {
            var currentText = editTextarea.textContent;

            // Match the typo in a case insensitive manner
			//var typoPattern = new RegExp('\\b' + typo + '\\b', 'gi');
			//not so sure i should use word boundaries
			//gi = global+caseinsensitive
            var typoPattern = new RegExp(typo, 'gi');
            
            var newText = currentText.replace(typoPattern, function(match) {
                if (match.charAt(0) === match.charAt(0).toUpperCase()) {
                    return typofix.charAt(0).toUpperCase() + typofix.slice(1);
                } else {
                    return typofix.toLowerCase();
                }
            });

            editTextarea.textContent = newText;

            if (editTextarea.textContent.includes(typofix)) {
                // Fill in the edit summary before clicking the "Show changes" button
                var changeSummary = typo + ' → ' + typofix;
                var editSummaryField = document.getElementById('wpSummary');
                if (editSummaryField) {
                    editSummaryField.value = changeSummary;
                }

                var showChangesButton = document.querySelector('input[name="wpDiff"]');
                if (showChangesButton) {
                    showChangesButton.click();
                }
            } else {
                console.log("Replacement text not found in the edit textarea.");
            }
        }
    }

    var typo = getUrlParameter('typo');
    var typofix = getUrlParameter('typofix');
    if (typo && typofix && typo !== '' && typofix !== '') {
        replaceTextInWikitextEditor(typo, typofix);
    }
});
// </nowiki>