es6.regexp.match.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. 'use strict';
  2. var anObject = require('./_an-object');
  3. var toLength = require('./_to-length');
  4. var advanceStringIndex = require('./_advance-string-index');
  5. var regExpExec = require('./_regexp-exec-abstract');
  6. // @@match logic
  7. require('./_fix-re-wks')('match', 1, function (defined, MATCH, $match, maybeCallNative) {
  8. return [
  9. // `String.prototype.match` method
  10. // https://tc39.github.io/ecma262/#sec-string.prototype.match
  11. function match(regexp) {
  12. var O = defined(this);
  13. var fn = regexp == undefined ? undefined : regexp[MATCH];
  14. return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[MATCH](String(O));
  15. },
  16. // `RegExp.prototype[@@match]` method
  17. // https://tc39.github.io/ecma262/#sec-regexp.prototype-@@match
  18. function (regexp) {
  19. var res = maybeCallNative($match, regexp, this);
  20. if (res.done) return res.value;
  21. var rx = anObject(regexp);
  22. var S = String(this);
  23. if (!rx.global) return regExpExec(rx, S);
  24. var fullUnicode = rx.unicode;
  25. rx.lastIndex = 0;
  26. var A = [];
  27. var n = 0;
  28. var result;
  29. while ((result = regExpExec(rx, S)) !== null) {
  30. var matchStr = String(result[0]);
  31. A[n] = matchStr;
  32. if (matchStr === '') rx.lastIndex = advanceStringIndex(S, toLength(rx.lastIndex), fullUnicode);
  33. n++;
  34. }
  35. return n === 0 ? null : A;
  36. }
  37. ];
  38. });