User:Mike Dillon/Scripts/replace.js

// Requires: User:Mike Dillon/Scripts/cookies.js, User:Mike Dillon/Scripts/i18n.js

/* 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:");

$(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; }; });