UNPKG

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