index.js 918 B

12345678910111213141516171819202122232425262728293031323334353637383940
  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. };