User:Polygnotus/DeDuplicateReferences.js

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.
// <nowiki>

//merges multiple instances of <ref>{{Harvnb|Heale|1990}} {{page numbers|}}</ref>
//with the same author, year and page number

mw.hook('wikipage.content').add(function ($content) {
    if (mw.config.get('wgAction') === 'edit') {
        var $button = $('<button>')
            .text('Process References')
            .css({
                'margin': '10px',
                'padding': '5px 10px',
                'background-color': '#36c',
                'color': 'white',
                'border': 'none',
                'border-radius': '3px',
                'cursor': 'pointer'
            });

        $button.on('click', function() {
            var text = $('#wpTextbox1').val();
            var refRegex = /<ref>(.*?)<\/ref>/g;
            var refs = [];
            var match;

            while ((match = refRegex.exec(text)) !== null) {
                refs.push(match[0]); // Store the entire <ref>...</ref> tag
            }

            console.log("Found references:", refs);

            // Count occurrences of each unique reference
            var refCounts = {};
            refs.forEach(function(ref) {
                refCounts[ref] = (refCounts[ref] || 0) + 1;
            });

            // Process references
            var processedRefs = {};
            Object.keys(refCounts).forEach(function(ref, index) {
                if (refCounts[ref] > 1) {
                    // This ref appears multiple times, so we'll create a named reference
                    var harvnbMatch = ref.match(/{{Harvnb\|(.*?)\|(.*?)}}/);
                    var pageMatch = ref.match(/{{page numbers\|(.*?)}}/);
                    var refName = 'ref' + (index + 1); // Default name

                    if (harvnbMatch && pageMatch) {
                        var author = harvnbMatch[1];
                        var year = harvnbMatch[2];
                        var page = pageMatch[1];
                        refName = author + '-' + year + '-' + page;
                    }
                    
                    processedRefs[ref] = {
                        first: ref.replace('<ref>', '<ref name="' + refName + '">'),
                        subsequent: '<ref name="' + refName + '" />'
                    };
                } else {
                    // This ref appears only once, leave it as is
                    processedRefs[ref] = {
                        first: ref,
                        subsequent: ref
                    };
                }
            });

            // Replace references in the text
            Object.keys(processedRefs).forEach(function(originalRef) {
                var processedRef = processedRefs[originalRef];
                
                // Replace first occurrence
                text = text.replace(originalRef, processedRef.first);
                
                // Replace subsequent occurrences if any
                if (processedRef.first !== processedRef.subsequent) {
                    var escapedOriginalRef = originalRef.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
                    text = text.replace(new RegExp(escapedOriginalRef, 'g'), processedRef.subsequent);
                }
            });

            $('#wpTextbox1').val(text);

            console.log("Processed references:", processedRefs);
            console.log("Text updated with processed references.");
        });

        $('#firstHeadingTitle').before($button);
    }
});

// </nowiki>