私の提案:
javascript で後読みを模倣します (ただし、このハックは完全ではない可能性があります)。
再帰降下パーサー (おそらく antlr) を使用しますか?
または、手動でコードを記述してそれを実行します。以下は、私が考えているものの最初のドラフトバージョンです (まだいくつかの疑似コードがあります):
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/>');
}
}