es.string.search.js 1.6 KB

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