1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- 'use strict';
- module.exports = function matchesStringOrRegExp(input, comparison) {
- if (!Array.isArray(input)) {
- return testAgainstStringOrRegExpOrArray(input, comparison);
- }
- for (const inputItem of input) {
- const testResult = testAgainstStringOrRegExpOrArray(inputItem, comparison);
- if (testResult) {
- return testResult;
- }
- }
- return false;
- };
- function testAgainstStringOrRegExpOrArray(value, comparison) {
- if (!Array.isArray(comparison)) {
- return testAgainstStringOrRegExp(value, comparison);
- }
- for (const comparisonItem of comparison) {
- const testResult = testAgainstStringOrRegExp(value, comparisonItem);
- if (testResult) {
- return testResult;
- }
- }
- return false;
- }
- function testAgainstStringOrRegExp(value, comparison) {
-
- if (comparison instanceof RegExp) {
- const match = value.match(comparison);
- return match ? { match: value, pattern: comparison, substring: match[0] || '' } : false;
- }
-
- const firstComparisonChar = comparison[0];
- const lastComparisonChar = comparison[comparison.length - 1];
- const secondToLastComparisonChar = comparison[comparison.length - 2];
- const comparisonIsRegex =
- firstComparisonChar === '/' &&
- (lastComparisonChar === '/' ||
- (secondToLastComparisonChar === '/' && lastComparisonChar === 'i'));
- const hasCaseInsensitiveFlag = comparisonIsRegex && lastComparisonChar === 'i';
-
- if (comparisonIsRegex) {
- const valueMatch = hasCaseInsensitiveFlag
- ? value.match(new RegExp(comparison.slice(1, -2), 'i'))
- : value.match(new RegExp(comparison.slice(1, -1)));
- return valueMatch
- ? { match: value, pattern: comparison, substring: valueMatch[0] || '' }
- : false;
- }
-
- return value === comparison ? { match: value, pattern: comparison, substring: value } : false;
- }
|