util-ex
Version:
Browser-friendly enhanced util fully compatible with standard node.js
34 lines (33 loc) • 912 B
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
exports.isRegExpStr = isRegExpStr;
/**
* Determines if a string represents a valid JavaScript RegExp.
* @param {string} aRegExpString - The string to test.
* @returns {boolean} - True if the string represents a valid EegExp, false otherwise.
* @example
* isRegExpStr('/[a-z]/g') // true
* isRegExpStr('/not a regexp') // false
*/
function isRegExpStr(value) {
let result = typeof value === 'string' && value.length > 2 && value[0] === '/';
if (result) {
const i = value.lastIndexOf('/');
if (i <= 0) {
result = false;
} else {
const source = value.slice(1, i);
const flags = value.slice(i + 1);
try {
new RegExp(source, flags);
} catch (e) {
result = false;
}
}
}
return result;
}
var _default = exports.default = isRegExpStr;