containsString.js 1.2 KB

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