function htmlSpecialChars(str) { str = str.replace(/&/g, '&'); str = str.replace(/</g, '<'); str = str.replace(/>/g, '>'); str = str.replace(/"/g, '"'); str = str.replace(/'/g, '''); return str; } //这个版本多转换了一些内容 function htmlSpecialChars(str) { var s = ""; if (str.length == 0) return ""; for (var i=0; i<str.length; i++) { switch (str.substr(i,1)) { case "<": s += "<"; break; case ">": s += ">"; break; case "&": s += "&"; break; case " ": if(str.substr(i + 1, 1) == " "){ s += " "; i++; } else s += " "; break; case """: s += """; break; case " ": s += "<br>"; break; default: s += str.substr(i,1); break; } } return s; }