Jump to content

User:Mike Dillon/Scripts/replace.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.
// Requires: [[User:Mike Dillon/Scripts/cookies.js]], [[User:Mike Dillon/Scripts/i18n.js]]

/* <pre><nowiki> */

/* Messages */
wfAddMsg("en", "regexReplaceLabel", "Regex replace");
wfAddMsg("en", "regexReplaceTitle", "Replace text in the edit window using regular expressions");
wfAddMsg("en", "regexReplaceSearchPrompt", "Search regex");
wfAddMsg("en", "regexReplaceReplacementPrompt", "Replace /$1/ with:");

addOnloadHook(function () {
    if (!document.forms.editform) return;

    var item = mw.util.addPortletLink('p-tb', '#', wfMsg("regexReplaceLabel"), 'ca-replace',
        wfMsg("regexReplaceTitle"), 'g', document.getElementById('ca-history'));

    var lastSearch = readCookie("lastRegexSearch");
    lastSearch = (lastSearch && lastSearch.length) ? decodeURIComponent(lastSearch) : "";

    var lastReplace = readCookie("lastRegexReplace");
    lastReplace = (lastReplace && lastReplace.length) ? decodeURIComponent(lastReplace) : "";

    item.getElementsByTagName("a")[0].onclick = function () {
        var s = prompt(wfMsg("regexReplaceSearchPrompt") + ":", lastSearch);
        if (!s) return false;

        var r = prompt(
            wfMsg("regexReplaceReplacementPrompt", s.replace(/\//g, "\\/")) + ":",
            lastReplace);
        if(r == null) return false;

        var txt = document.editform.wpTextbox1;
        txt.value = txt.value.replace(new RegExp(s, "mg"), r);

        lastSearch = s;
        lastReplace = r;

        writeCookie("lastRegexSearch", encodeURIComponent(lastSearch), { "path": "/" });
        writeCookie("lastRegexReplace", encodeURIComponent(lastReplace), { "path": "/" });

        return false;
    };
});

/* </nowiki></pre> */