es.string.search.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637
  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 requireObjectCoercible = require('../internals/require-object-coercible');
  6. var sameValue = require('../internals/same-value');
  7. var toString = require('../internals/to-string');
  8. var getMethod = require('../internals/get-method');
  9. var regExpExec = require('../internals/regexp-exec-abstract');
  10. // @@search logic
  11. fixRegExpWellKnownSymbolLogic('search', function (SEARCH, nativeSearch, maybeCallNative) {
  12. return [
  13. // `String.prototype.search` method
  14. // https://tc39.es/ecma262/#sec-string.prototype.search
  15. function search(regexp) {
  16. var O = requireObjectCoercible(this);
  17. var searcher = regexp == undefined ? undefined : getMethod(regexp, SEARCH);
  18. return searcher ? call(searcher, regexp, O) : new RegExp(regexp)[SEARCH](toString(O));
  19. },
  20. // `RegExp.prototype[@@search]` method
  21. // https://tc39.es/ecma262/#sec-regexp.prototype-@@search
  22. function (string) {
  23. var rx = anObject(this);
  24. var S = toString(string);
  25. var res = maybeCallNative(nativeSearch, rx, S);
  26. if (res.done) return res.value;
  27. var previousLastIndex = rx.lastIndex;
  28. if (!sameValue(previousLastIndex, 0)) rx.lastIndex = 0;
  29. var result = regExpExec(rx, S);
  30. if (!sameValue(rx.lastIndex, previousLastIndex)) rx.lastIndex = previousLastIndex;
  31. return result === null ? -1 : result.index;
  32. }
  33. ];
  34. });