Jump to content

User:Certes/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.
/*** Find and replace ***/
// Replaces text re1from → re1to, etc.
// Uses URL parameters ?action=edit&re1from=...&re1to=...&re1flags=...[&re2from=...&re2to=...&re2flags=...]...

function replace(str) {
    // Parse URL parameters:
    // re1from, re1to, re1flags: replaces regexp /re1from/re1flags by text "re1to"
    // re2from, re2to, re2flags ... re10from, re10to, re10flags: further replacements
    const param = location.search && location.search.substr(1).replace(/\+/gi," ").split("&");
    for (var i in param) { // parse URL variables e.g. &re1from=Foo
        var s = param[i].split("=");
        param[i] = param[unescape(s[0])] = unescape(s[1]);
    }

	var refrom = [];
	var reto = [];
	var recount = 0;
	for (i = 1; i <= 10; i++) { // Look for re1from etc.
		var rf = param['re' + String(i) + 'from'];
		if (rf) {
			refrom[recount] = new RegExp(rf, decodeURIComponent(param['re' + String(i) + 'flags'] || ''));
			reto[recount] = decodeURIComponent(param['re' + String(i) + 'to'] || '');
			recount ++;
		}
	}
    for (i = 0; i < recount; i++) {
        str = str.replace(refrom[i], reto[i] || '');
    }
    return str;
};