esnext.regexp.escape.js 1.0 KB

12345678910111213141516171819202122232425
  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 padStart = require('../internals/string-pad').start;
  6. var WHITESPACES = require('../internals/whitespaces');
  7. var charCodeAt = uncurryThis(''.charCodeAt);
  8. var replace = uncurryThis(''.replace);
  9. var numberToString = uncurryThis(1.1.toString);
  10. var NEED_ESCAPING = RegExp('[!"#$%&\'()*+,\\-./:;<=>?@[\\\\\\]^`{|}~' + WHITESPACES + ']', 'g');
  11. // `RegExp.escape` method
  12. // https://github.com/tc39/proposal-regex-escaping
  13. $({ target: 'RegExp', stat: true, forced: true }, {
  14. escape: function escape(S) {
  15. var str = toString(S);
  16. var firstCode = charCodeAt(str, 0);
  17. // escape first DecimalDigit
  18. return (firstCode > 47 && firstCode < 58 ? '\\x3' : '') + replace(str, NEED_ESCAPING, function (match) {
  19. var hex = numberToString(charCodeAt(match, 0), 16);
  20. return hex.length < 3 ? '\\x' + padStart(hex, 2, '0') : '\\u' + padStart(hex, 4, '0');
  21. });
  22. }
  23. });