es.string.search.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334
  1. 'use strict';
  2. var fixRegExpWellKnownSymbolLogic = require('../internals/fix-regexp-well-known-symbol-logic');
  3. var anObject = require('../internals/an-object');
  4. var requireObjectCoercible = require('../internals/require-object-coercible');
  5. var sameValue = require('../internals/same-value');
  6. var regExpExec = require('../internals/regexp-exec-abstract');
  7. // @@search logic
  8. fixRegExpWellKnownSymbolLogic('search', 1, function (SEARCH, nativeSearch, maybeCallNative) {
  9. return [
  10. // `String.prototype.search` method
  11. // https://tc39.github.io/ecma262/#sec-string.prototype.search
  12. function search(regexp) {
  13. var O = requireObjectCoercible(this);
  14. var searcher = regexp == undefined ? undefined : regexp[SEARCH];
  15. return searcher !== undefined ? searcher.call(regexp, O) : new RegExp(regexp)[SEARCH](String(O));
  16. },
  17. // `RegExp.prototype[@@search]` method
  18. // https://tc39.github.io/ecma262/#sec-regexp.prototype-@@search
  19. function (regexp) {
  20. var res = maybeCallNative(nativeSearch, regexp, this);
  21. if (res.done) return res.value;
  22. var rx = anObject(regexp);
  23. var S = String(this);
  24. var previousLastIndex = rx.lastIndex;
  25. if (!sameValue(previousLastIndex, 0)) rx.lastIndex = 0;
  26. var result = regExpExec(rx, S);
  27. if (!sameValue(rx.lastIndex, previousLastIndex)) rx.lastIndex = previousLastIndex;
  28. return result === null ? -1 : result.index;
  29. }
  30. ];
  31. });