escape.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. // Declare internals
  2. var internals = {};
  3. exports.escapeJavaScript = function (input) {
  4. if (!input) {
  5. return '';
  6. }
  7. var escaped = '';
  8. for (var i = 0, il = input.length; i < il; ++i) {
  9. var charCode = input.charCodeAt(i);
  10. if (internals.isSafe(charCode)) {
  11. escaped += input[i];
  12. }
  13. else {
  14. escaped += internals.escapeJavaScriptChar(charCode);
  15. }
  16. }
  17. return escaped;
  18. };
  19. exports.escapeHtml = function (input) {
  20. if (!input) {
  21. return '';
  22. }
  23. var escaped = '';
  24. for (var i = 0, il = input.length; i < il; ++i) {
  25. var charCode = input.charCodeAt(i);
  26. if (internals.isSafe(charCode)) {
  27. escaped += input[i];
  28. }
  29. else {
  30. escaped += internals.escapeHtmlChar(charCode);
  31. }
  32. }
  33. return escaped;
  34. };
  35. internals.escapeJavaScriptChar = function (charCode) {
  36. if (charCode >= 256) {
  37. return '\\u' + internals.padLeft('' + charCode, 4);
  38. }
  39. var hexValue = new Buffer(String.fromCharCode(charCode), 'ascii').toString('hex');
  40. return '\\x' + internals.padLeft(hexValue, 2);
  41. };
  42. internals.escapeHtmlChar = function (charCode) {
  43. var namedEscape = internals.namedHtml[charCode];
  44. if (typeof namedEscape !== 'undefined') {
  45. return namedEscape;
  46. }
  47. if (charCode >= 256) {
  48. return '&#' + charCode + ';';
  49. }
  50. var hexValue = new Buffer(String.fromCharCode(charCode), 'ascii').toString('hex');
  51. return '&#x' + internals.padLeft(hexValue, 2) + ';';
  52. };
  53. internals.padLeft = function (str, len) {
  54. while (str.length < len) {
  55. str = '0' + str;
  56. }
  57. return str;
  58. };
  59. internals.isSafe = function (charCode) {
  60. return (typeof internals.safeCharCodes[charCode] !== 'undefined');
  61. };
  62. internals.namedHtml = {
  63. '38': '&amp;',
  64. '60': '&lt;',
  65. '62': '&gt;',
  66. '34': '&quot;',
  67. '160': '&nbsp;',
  68. '162': '&cent;',
  69. '163': '&pound;',
  70. '164': '&curren;',
  71. '169': '&copy;',
  72. '174': '&reg;'
  73. };
  74. internals.safeCharCodes = (function () {
  75. var safe = {};
  76. for (var i = 32; i < 123; ++i) {
  77. if ((i >= 97) || // a-z
  78. (i >= 65 && i <= 90) || // A-Z
  79. (i >= 48 && i <= 57) || // 0-9
  80. i === 32 || // space
  81. i === 46 || // .
  82. i === 44 || // ,
  83. i === 45 || // -
  84. i === 58 || // :
  85. i === 95) { // _
  86. safe[i] = null;
  87. }
  88. }
  89. return safe;
  90. }());