User:Quarl/autoreplace.js
Appearance
Code that you insert on this page could contain malicious content capable of compromising your account. If you import a script from another page with "importScript", "mw.loader.load", "iusc", or "lusc", take note that this causes you to dynamically load a remote script, which could be changed by others. Editors are responsible for all edits and actions they perform, including by scripts. User scripts are not centrally supported and may malfunction or become inoperable due to software changes. A guide to help you find broken scripts is available. If you are unsure whether code you are adding to this page is safe, you can ask at the appropriate village pump. This code will be executed when previewing this page. |
Documentation for this user script can be added at User:Quarl/autoreplace. |
// [[User:Quarl/autoreplace.js]] - provides capability to replace strings (regular expressions) in edit boxes on submission.
// Strings between <nowiki> ... </nowiki> are not replaced.
// depends: wikipage.js, wikiedit.js, util.js
// recommends: smartsubmit.js
// external entry points:
// autoreplace.addReplacement("string", "replacement" || replacement_function);
// quarl 2006-01-04 initial version
// test:
// javascript:alert(autoreplace_replace_string_nonowiki("2 x 3 <nowiki> 4 x 5 </nowiki> 6", "x", "XXX"))
// javascript:alert(autoreplace_replace_strings("a ~~"+"~~ foo <nowiki>~~"+"~~</nowiki>"))
// <pre><nowiki>
autoreplace = new Object();
autoreplace.enabled = true;
autoreplace.replacements = Array();
// add a replacement
autoreplace.addReplacement = function(str, replacement) {
autoreplace.replacements.push([str,replacement]);
}
// deprecated
autoreplace_add = autoreplace.addReplacement;
autoreplace.fToStr = function(t) {
if (typeof t == 'function') t = t();
return ""+t;
}
autoreplace.replaceString = function(text, str, replacement) {
return text.replace(new RegExp(str,'g'), replacement);
}
autoreplace.replaceStringNoNowiki = function(text, str, replacement) {
var rtext = '';
while ( text.match(/<nowiki>(?:.|\n)*?<\/nowiki>|<!--(?:.|\n)*?-->/) ) {
// save these before they get clobbered!
var left = RegExp.leftContext;
var match = RegExp.lastMatch;
var right = RegExp.rightContext;
rtext += autoreplace.replaceString(left, str, replacement) + match;
text = right;
}
rtext += autoreplace.replaceString(text, str, replacement)
return rtext;
}
autoreplace.replaceStrings = function(text) {
if (!text) return text;
for (i in autoreplace.replacements) {
r = autoreplace.replacements[i];
text = autoreplace.replaceStringNoNowiki(text, r[0], autoreplace.fToStr(r[1]));
}
return text;
}
autoreplace.preSubmitHook = function(editor, data, button) {
if (!autoreplace.enabled) return;
if (!data.wpTextbox1) return;
data.wpTextbox1 = autoreplace.replaceStrings(data.wpTextbox1);
}
autoreplace.load = function() {
WikiEditor.addPreSubmitHook(autoreplace.preSubmitHook);
}
$(autoreplace.load);
// </nowiki></pre>