Node-Red configuration
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

esnext.regexp.escape.js 2.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. 'use strict';
  2. var $ = require('../internals/export');
  3. var uncurryThis = require('../internals/function-uncurry-this');
  4. var aString = require('../internals/a-string');
  5. var hasOwn = require('../internals/has-own-property');
  6. var padStart = require('../internals/string-pad').start;
  7. var WHITESPACES = require('../internals/whitespaces');
  8. var $Array = Array;
  9. var $escape = RegExp.escape;
  10. var charAt = uncurryThis(''.charAt);
  11. var charCodeAt = uncurryThis(''.charCodeAt);
  12. var numberToString = uncurryThis(1.1.toString);
  13. var join = uncurryThis([].join);
  14. var FIRST_DIGIT_OR_ASCII = /^[0-9a-z]/i;
  15. var SYNTAX_SOLIDUS = /^[$()*+./?[\\\]^{|}]/;
  16. var OTHER_PUNCTUATORS_AND_WHITESPACES = RegExp('^[!"#%&\',\\-:;<=>@`~' + WHITESPACES + ']');
  17. var exec = uncurryThis(FIRST_DIGIT_OR_ASCII.exec);
  18. var ControlEscape = {
  19. '\u0009': 't',
  20. '\u000A': 'n',
  21. '\u000B': 'v',
  22. '\u000C': 'f',
  23. '\u000D': 'r'
  24. };
  25. var escapeChar = function (chr) {
  26. var hex = numberToString(charCodeAt(chr, 0), 16);
  27. return hex.length < 3 ? '\\x' + padStart(hex, 2, '0') : '\\u' + padStart(hex, 4, '0');
  28. };
  29. // Avoiding the use of polyfills of the previous iteration of this proposal
  30. var FORCED = !$escape || $escape('ab') !== '\\x61b';
  31. // `RegExp.escape` method
  32. // https://github.com/tc39/proposal-regex-escaping
  33. $({ target: 'RegExp', stat: true, forced: FORCED }, {
  34. escape: function escape(S) {
  35. aString(S);
  36. var length = S.length;
  37. var result = $Array(length);
  38. for (var i = 0; i < length; i++) {
  39. var chr = charAt(S, i);
  40. if (i === 0 && exec(FIRST_DIGIT_OR_ASCII, chr)) {
  41. result[i] = escapeChar(chr);
  42. } else if (hasOwn(ControlEscape, chr)) {
  43. result[i] = '\\' + ControlEscape[chr];
  44. } else if (exec(SYNTAX_SOLIDUS, chr)) {
  45. result[i] = '\\' + chr;
  46. } else if (exec(OTHER_PUNCTUATORS_AND_WHITESPACES, chr)) {
  47. result[i] = escapeChar(chr);
  48. } else {
  49. var charCode = charCodeAt(chr, 0);
  50. // single UTF-16 code unit
  51. if ((charCode & 0xF800) !== 0xD800) result[i] = chr;
  52. // unpaired surrogate
  53. else if (charCode >= 0xDC00 || i + 1 >= length || (charCodeAt(S, i + 1) & 0xFC00) !== 0xDC00) result[i] = escapeChar(chr);
  54. // surrogate pair
  55. else {
  56. result[i] = chr;
  57. result[++i] = charAt(S, i);
  58. }
  59. }
  60. }
  61. return join(result, '');
  62. }
  63. });