htmlescape.js 863 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. /**
  2. * Properly escape JSON for usage as an object literal inside of a `<script>` tag.
  3. * JS implementation of http://golang.org/pkg/encoding/json/#HTMLEscape
  4. * More info: http://timelessrepo.com/json-isnt-a-javascript-subset
  5. */
  6. 'use strict';
  7. var ESCAPE_LOOKUP = {
  8. '&': '\\u0026',
  9. '>': '\\u003e',
  10. '<': '\\u003c',
  11. '\u2028': '\\u2028',
  12. '\u2029': '\\u2029'
  13. };
  14. var ESCAPE_REGEX = /[&><\u2028\u2029]/g;
  15. function escaper(match) {
  16. return ESCAPE_LOOKUP[match];
  17. }
  18. module.exports = function(obj) {
  19. return JSON.stringify(obj).replace(ESCAPE_REGEX, escaper);
  20. };
  21. /***/
  22. var TERMINATORS_LOOKUP = {
  23. '\u2028': '\\u2028',
  24. '\u2029': '\\u2029'
  25. };
  26. var TERMINATORS_REGEX = /[\u2028\u2029]/g;
  27. function sanitizer(match) {
  28. return TERMINATORS_LOOKUP[match];
  29. }
  30. module.exports.sanitize = function(str) {
  31. return str.replace(TERMINATORS_REGEX, sanitizer);
  32. };