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.
// Does what it says on the tin. Adds a portlet link to the tab bar which allows the user to replace a phrase with another.
// Code by [[User:Fox]], fixed extensively by [[User:Tom Morris]], with help from [[User:Quanticle]].

addOnloadHook(function() {
    // parse URL parameters into an object
    var urlParameters = (function() {
        var urlParameters = new Object();
        var asReadInUrlParameters;
        var asReadInUrlParameter;

        asReadInUrlParameters = location.search.substring(1, location.search.length).split("&");
        for (i = 0; i < asReadInUrlParameters.length; i++) {
            asReadInUrlParameter = asReadInUrlParameters[i].split("=");
            urlParameters[decodeURIComponent(asReadInUrlParameter[0])] = decodeURIComponent(asReadInUrlParameter[1]);
        }
        
        return urlParameters;
    })();

    // handle what happens if there is a 'replace'
    if (urlParameters["action"] == "edit" && urlParameters["replace"] != undefined) {
      
        // prompt the user
        var before = prompt("What do you want to replace?", "");
        var after = prompt("What do you want to replace \"" + before + "\" with?", "");
        
        // replace text
        var match = new RegExp(before, "ig");
        var form = document.forms["editform"];
        var txt = form["wpTextbox1"].value;

        if (after.length > 0 && before.length > 0) {
            replaced = txt.replace(match, after);
        } else {
            alert("You must specify both variables!")
        }
        
        form["wpTextbox1"].value = replaced;
        // set edit summary
        form["wpSummary"].value = 'Replacing the phrase ' + before + ' with ' + after + ' ([[User:Fox/replace.js|RPL]])';
        // submit
        form.submit();
    }

    // add portlet link
    mw.util.addPortletLink("p-cactions", wgScript + "?title=" + wgPageName + "&action=edit&replace=1", "replace", "ca-replace");
});