User:Polygnotus/Scripts/DiffCompare.js

This is an old revision of this page, as edited by Polygnotus (talk | contribs) at 21:51, 8 September 2024. 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.
$.ajax('https://cdn.jsdelivr.net/gh/google/diff-match-patch@master/javascript/diff_match_patch.js', {
    dataType: 'script',
    cache: true
}).then(function () {
    if (typeof diff_match_patch === 'undefined') {
        console.error('diff_match_patch library not loaded');
        return;
    }

    function showDiff(text1, text2) {
        const dmp = new diff_match_patch();
        const diffs = dmp.diff_main(text1, text2);
        dmp.diff_cleanupSemantic(diffs);

        let html = '';
        for (let i = 0; i < diffs.length; i++) {
            const [op, data] = diffs[i];
            switch (op) {
                case diff_match_patch.DIFF_INSERT:
                    html += '<ins style="background-color: #e6ffe6;">' + escapeHtml(data) + '</ins>';
                    break;
                case diff_match_patch.DIFF_DELETE:
                    html += '<del style="background-color: #ffe6e6;">' + escapeHtml(data) + '</del>';
                    break;
                case diff_match_patch.DIFF_EQUAL:
                    html += '<span>' + escapeHtml(data) + '</span>';
                    break;
            }
        }
        return html;
    }

    function escapeHtml(unsafe) {
        return unsafe
            .replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;")
            .replace(/'/g, "&#039;");
    }

    const oldText = "The quick brown fox jumps over the lazy dog.";
    const newText = "The fast brown fox leaps over the lazy cat.";

    try {
        const diffHtml = showDiff(oldText, newText);
        console.log('Diff result:', diffHtml);
        // $('#diff-output').html(diffHtml);
    } catch (error) {
        console.error('Error generating diff:', error);
    }
}).catch(function(error) {
    console.error('Error loading diff_match_patch library:', error);
});