My suggestions:
mimic lookbehind in javascript (though this hack may not be perfect).
use a recursive descent parser (maybe antlr)?
Or manually write code to do it for you. Below is my first draft version of what I'm thinking (there's still some pseudo-code ):
function go(str) {
var quoteStart, quoteEnd, quotedRanges, from, retval;
quotedRanges = []; //quotedRanges holds the indexes inclusively within which nothing should be changed because it's quoted.
quoteStart = str.indexOf('"');
if( quoteStart > -1 ) {
from = quoteStart;
while (from !== false) {
quoteEnd = str.indexOf('"', from);
if (quoteEnd == -1) { //There is an unmatched quote. We pretend that it is closed off at the end of the string.
quoteEnd = str.len;
from = false;
} else if(str.charAt(quoteEnd - 1) == "\\") {
from = quoteEnd;
} else { //we found the ending quote index.
from = false;
}
}
quotedRanges.push([quoteStart, quoteEnd]);
}
retval = str.replace(/(function|new|return|var)?\s/g, function($0, $statement) {
if($0 within on of quotedRanges)
return $0;
return $statement ? $0 : '';
});
return retval;
}
assert(1, go("") == "");
assert(2, go("function ") == "function ");
assert(3, go(" ") == "");
assert(4, go('" "') == '" "');
assert(5, go('" ') == '" ');
assert(6, go('"x x"') == '"x x"');
assert(6, go('"new x"') == '"new x"');
assert(7, go(' "x x"') == '"x x"');
assert(8, go("' '") == "' '");
assert(9, go("' \\' '") == "' \\' '");
function assert(num, statement) {
if(!statement) {
document.write('test #' + num + ' failed! <br/>');
}
}