UNPKG

util-ex

Version:

Browser-friendly enhanced util fully compatible with standard node.js

28 lines (27 loc) 753 B
/** * 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 */ export 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 } export default isRegExpStr;