es.escape.js 867 B

123456789101112131415161718192021222324252627282930313233343536
  1. 'use strict';
  2. var $ = require('../internals/export');
  3. var toString = require('../internals/to-string');
  4. var raw = /[\w*+\-./@]/;
  5. var hex = function (code, length) {
  6. var result = code.toString(16);
  7. while (result.length < length) result = '0' + result;
  8. return result;
  9. };
  10. // `escape` method
  11. // https://tc39.es/ecma262/#sec-escape-string
  12. $({ global: true }, {
  13. escape: function escape(string) {
  14. var str = toString(string);
  15. var result = '';
  16. var length = str.length;
  17. var index = 0;
  18. var chr, code;
  19. while (index < length) {
  20. chr = str.charAt(index++);
  21. if (raw.test(chr)) {
  22. result += chr;
  23. } else {
  24. code = chr.charCodeAt(0);
  25. if (code < 256) {
  26. result += '%' + hex(code, 2);
  27. } else {
  28. result += '%u' + hex(code, 4).toUpperCase();
  29. }
  30. }
  31. } return result;
  32. }
  33. });