es.string.match.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. 'use strict';
  2. var call = require('../internals/function-call');
  3. var fixRegExpWellKnownSymbolLogic = require('../internals/fix-regexp-well-known-symbol-logic');
  4. var anObject = require('../internals/an-object');
  5. var isNullOrUndefined = require('../internals/is-null-or-undefined');
  6. var toLength = require('../internals/to-length');
  7. var toString = require('../internals/to-string');
  8. var requireObjectCoercible = require('../internals/require-object-coercible');
  9. var getMethod = require('../internals/get-method');
  10. var advanceStringIndex = require('../internals/advance-string-index');
  11. var regExpExec = require('../internals/regexp-exec-abstract');
  12. // @@match logic
  13. fixRegExpWellKnownSymbolLogic('match', function (MATCH, nativeMatch, maybeCallNative) {
  14. return [
  15. // `String.prototype.match` method
  16. // https://tc39.es/ecma262/#sec-string.prototype.match
  17. function match(regexp) {
  18. var O = requireObjectCoercible(this);
  19. var matcher = isNullOrUndefined(regexp) ? undefined : getMethod(regexp, MATCH);
  20. return matcher ? call(matcher, regexp, O) : new RegExp(regexp)[MATCH](toString(O));
  21. },
  22. // `RegExp.prototype[@@match]` method
  23. // https://tc39.es/ecma262/#sec-regexp.prototype-@@match
  24. function (string) {
  25. var rx = anObject(this);
  26. var S = toString(string);
  27. var res = maybeCallNative(nativeMatch, rx, S);
  28. if (res.done) return res.value;
  29. if (!rx.global) return regExpExec(rx, S);
  30. var fullUnicode = rx.unicode;
  31. rx.lastIndex = 0;
  32. var A = [];
  33. var n = 0;
  34. var result;
  35. while ((result = regExpExec(rx, S)) !== null) {
  36. var matchStr = toString(result[0]);
  37. A[n] = matchStr;
  38. if (matchStr === '') rx.lastIndex = advanceStringIndex(S, toLength(rx.lastIndex), fullUnicode);
  39. n++;
  40. }
  41. return n === 0 ? null : A;
  42. }
  43. ];
  44. });