日期:2014-05-16  浏览次数:20410 次

javascript执行eval函数时利用正则表达式去掉回车符换行符和注释
var txtValue = document.getElementById(txtId).value;
txtValue = txtValue.replace(/\/\*((\n|\r|.)*?)\*\//mg, ""); //去掉多行注释/*..*/
txtValue = txtValue.replace(/(\s+)\/\/(.*)\n/g,""); //去掉单行注释//(前面有空格的注释)
txtValue = txtValue.replace(/;\/\/(.*)\n/g,";"); //去掉单行注释//(前面是分号的注释)
txtValue = txtValue.replace(/\/\/[^"][^']\n/g,""); //去掉单行注释//(//后面只有一个'或一个"的不替换)
txtValue = txtValue.replace(/[\r]/g,""); //替换换行
txtValue = txtValue.replace(/[\n]/g,""); //替换回车
eval(txtValue);