Jump to content

User:SD0001/escapeRawPipes.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.
/**
 * Replaces raw pipes `|` in string with `{{!}}`
 * Doesn't replace pipes that are within a link or a template
 * Useful for strings to be passed as arguments to transcluded templates
 * @param {string} text
 * @requires MediaWiki:Gadget-morebits.js
 */
function escapeRawPipes (text) {

	// number of unclosed brackets
	var tlevel = 0, llevel = 0;

	var u = new Morebits.unbinder(text);
	u.unbind('<!--', '-->');
	u.unbind('<nowiki>', '</nowiki>');

	var n = u.content.length;
	for ( var i = 0; i < n; i++ ) {

		if (u.content[i] === '{' && u.content[i+1] === '{') {
			tlevel++;
			i++;
		} else if (u.content[i] === '[' && u.content[i+1] === '[') {
			llevel++;
			i++;
		} else if (u.content[i] === '}' && u.content[i+1] === '}') {
			tlevel--;
			i++;
		} else if (u.content[i] === ']' && u.content[i+1] === ']') {
			llevel--;
			i++;
		} else if (u.content[i] === '|' && tlevel === 0 && llevel === 0) {
			// swap out pipe with \1 character
			u.content = u.content.slice(0, i) + '\1' + u.content.slice(i + 1);
		}
	}

	return u.rebind().replace(/\1/g, '{{!}}');

}