escapeHtml.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. "use strict";
  2. const matchHtmlRegExp = /["'&<>]/;
  3. /**
  4. * @param {string} string raw HTML
  5. * @returns {string} escaped HTML
  6. */
  7. function escapeHtml(string) {
  8. const str = `${string}`;
  9. const match = matchHtmlRegExp.exec(str);
  10. if (!match) {
  11. return str;
  12. }
  13. let escape;
  14. let html = "";
  15. let index = 0;
  16. let lastIndex = 0;
  17. for (({
  18. index
  19. } = match); index < str.length; index++) {
  20. switch (str.charCodeAt(index)) {
  21. // "
  22. case 34:
  23. escape = "&quot;";
  24. break;
  25. // &
  26. case 38:
  27. escape = "&amp;";
  28. break;
  29. // '
  30. case 39:
  31. escape = "&#39;";
  32. break;
  33. // <
  34. case 60:
  35. escape = "&lt;";
  36. break;
  37. // >
  38. case 62:
  39. escape = "&gt;";
  40. break;
  41. default:
  42. // eslint-disable-next-line no-continue
  43. continue;
  44. }
  45. if (lastIndex !== index) {
  46. html += str.substring(lastIndex, index);
  47. }
  48. lastIndex = index + 1;
  49. html += escape;
  50. }
  51. return lastIndex !== index ? html + str.substring(lastIndex, index) : html;
  52. }
  53. module.exports = escapeHtml;