escapeJson.js 740 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. 'use strict';
  2. const internals = {};
  3. module.exports = function (input) {
  4. if (!input) {
  5. return '';
  6. }
  7. const lessThan = 0x3C;
  8. const greaterThan = 0x3E;
  9. const andSymbol = 0x26;
  10. const lineSeperator = 0x2028;
  11. // replace method
  12. let charCode;
  13. return input.replace(/[<>&\u2028\u2029]/g, (match) => {
  14. charCode = match.charCodeAt(0);
  15. if (charCode === lessThan) {
  16. return '\\u003c';
  17. }
  18. if (charCode === greaterThan) {
  19. return '\\u003e';
  20. }
  21. if (charCode === andSymbol) {
  22. return '\\u0026';
  23. }
  24. if (charCode === lineSeperator) {
  25. return '\\u2028';
  26. }
  27. return '\\u2029';
  28. });
  29. };