es6.regexp.search.js 1.2 KB

12345678910111213141516171819202122232425262728293031
  1. 'use strict';
  2. var anObject = require('./_an-object');
  3. var sameValue = require('./_same-value');
  4. var regExpExec = require('./_regexp-exec-abstract');
  5. // @@search logic
  6. require('./_fix-re-wks')('search', 1, function (defined, SEARCH, $search, maybeCallNative) {
  7. return [
  8. // `String.prototype.search` method
  9. // https://tc39.github.io/ecma262/#sec-string.prototype.search
  10. function search(regexp) {
  11. var O = defined(this);
  12. var fn = regexp == undefined ? undefined : regexp[SEARCH];
  13. return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[SEARCH](String(O));
  14. },
  15. // `RegExp.prototype[@@search]` method
  16. // https://tc39.github.io/ecma262/#sec-regexp.prototype-@@search
  17. function (regexp) {
  18. var res = maybeCallNative($search, regexp, this);
  19. if (res.done) return res.value;
  20. var rx = anObject(regexp);
  21. var S = String(this);
  22. var previousLastIndex = rx.lastIndex;
  23. if (!sameValue(previousLastIndex, 0)) rx.lastIndex = 0;
  24. var result = regExpExec(rx, S);
  25. if (!sameValue(rx.lastIndex, previousLastIndex)) rx.lastIndex = previousLastIndex;
  26. return result === null ? -1 : result.index;
  27. }
  28. ];
  29. });