containsString.cjs 1.4 KB

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