User:SD0001/escapeRawPipes.js

/** * 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(' ', ' ');

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, '|');

}