UNPKG

1.18 kBJavaScriptView Raw
1'use strict';
2
3const _ = require('lodash');
4
5/** @typedef {false | { match: string, pattern: string }} ReturnValue */
6
7/**
8 * Checks if a string contains a value. The comparison value can be a string or
9 * an array of strings.
10 *
11 * Any strings starting and ending with `/` are ignored. Use the
12 * matchesStringOrRegExp() util to match regexes.
13 *
14 * @param {string} input
15 * @param {string | string[]} comparison
16 *
17 * @returns {ReturnValue}
18 */
19module.exports = function containsString(input, comparison) {
20 if (!Array.isArray(comparison)) {
21 return testAgainstString(input, comparison);
22 }
23
24 for (const comparisonItem of comparison) {
25 const testResult = testAgainstString(input, comparisonItem);
26
27 if (testResult) {
28 return testResult;
29 }
30 }
31
32 return false;
33};
34
35/**
36 *
37 * @param {string} value
38 * @param {string} comparison
39 *
40 * @returns {ReturnValue}
41 */
42function testAgainstString(value, comparison) {
43 if (!comparison) return false;
44
45 if (!_.isString(comparison)) return false;
46
47 if (comparison.startsWith('/') && comparison.endsWith('/')) {
48 return false;
49 }
50
51 if (value.includes(comparison)) {
52 return { match: value, pattern: comparison };
53 }
54
55 return false;
56}