index.js 918 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. 'use strict';
  2. var has = require('has');
  3. var regexExec = RegExp.prototype.exec;
  4. var gOPD = Object.getOwnPropertyDescriptor;
  5. var tryRegexExecCall = function tryRegexExec(value) {
  6. try {
  7. var lastIndex = value.lastIndex;
  8. value.lastIndex = 0;
  9. regexExec.call(value);
  10. return true;
  11. } catch (e) {
  12. return false;
  13. } finally {
  14. value.lastIndex = lastIndex;
  15. }
  16. };
  17. var toStr = Object.prototype.toString;
  18. var regexClass = '[object RegExp]';
  19. var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
  20. module.exports = function isRegex(value) {
  21. if (!value || typeof value !== 'object') {
  22. return false;
  23. }
  24. if (!hasToStringTag) {
  25. return toStr.call(value) === regexClass;
  26. }
  27. var descriptor = gOPD(value, 'lastIndex');
  28. var hasLastIndexDataProperty = descriptor && has(descriptor, 'value');
  29. if (!hasLastIndexDataProperty) {
  30. return false;
  31. }
  32. return tryRegexExecCall(value);
  33. };