es.escape.js 1.1 KB

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