es.string.match.js 1.7 KB

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