index.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /*!
  2. * escape-html
  3. * Copyright(c) 2012-2013 TJ Holowaychuk
  4. * Copyright(c) 2015 Andreas Lubbe
  5. * Copyright(c) 2015 Tiancheng "Timothy" Gu
  6. * MIT Licensed
  7. */
  8. 'use strict';
  9. /**
  10. * Module variables.
  11. * @private
  12. */
  13. var matchHtmlRegExp = /["'&<>]/;
  14. /**
  15. * Module exports.
  16. * @public
  17. */
  18. module.exports = escapeHtml;
  19. /**
  20. * Escape special characters in the given string of html.
  21. *
  22. * @param {string} string The string to escape for inserting into HTML
  23. * @return {string}
  24. * @public
  25. */
  26. function escapeHtml(string) {
  27. var str = '' + string;
  28. var match = matchHtmlRegExp.exec(str);
  29. if (!match) {
  30. return str;
  31. }
  32. var escape;
  33. var html = '';
  34. var index = 0;
  35. var lastIndex = 0;
  36. for (index = match.index; index < str.length; index++) {
  37. switch (str.charCodeAt(index)) {
  38. case 34: // "
  39. escape = '&quot;';
  40. break;
  41. case 38: // &
  42. escape = '&amp;';
  43. break;
  44. case 39: // '
  45. escape = '&#39;';
  46. break;
  47. case 60: // <
  48. escape = '&lt;';
  49. break;
  50. case 62: // >
  51. escape = '&gt;';
  52. break;
  53. default:
  54. continue;
  55. }
  56. if (lastIndex !== index) {
  57. html += str.substring(lastIndex, index);
  58. }
  59. lastIndex = index + 1;
  60. html += escape;
  61. }
  62. return lastIndex !== index
  63. ? html + str.substring(lastIndex, index)
  64. : html;
  65. }