I think you shouldn't rely on regexps for these kind of tasks, since it would be overcomplicated and therefore slow. Anyway, if your expression is correct (i.e., for every "|code" there's a "code|" and there aren't nested code tags), you can try this:
var n = str.replace(/to(?!(?:\|(?!code)|[^\|])*code\|)/g, "2");
Not only it's complicated, but it's hard to maintain. The best thing to do in these cases is to split your string to chunks:
var chunks = [], i, p = 0, q = 0;
while ((p = str.indexOf("|code", p)) !== -1) {
if (q < p) chunks.push(str.substring(q, p));
q = str.indexOf("code|", p);
chunks.push(str.substring(p, p = q = q + 5));
}
if (q < str.length) chunks.push(str.substring(q));
// chunks === [" Would you like to have responses to your questions ",
// "|code Would you like to have responses to your questions code|",
// " Would you like to have responses to your questions "]
Note: str.replace("to", "2") does not replace every occurrence of "to", but only the first one.