Skip to content

createSafeMatcher

Like createMatcher, but returns null instead of throwing when a string pattern is an invalid regular expression, to report bad user input without a try.

Available since v3.1.5

import { createSafeMatcher } from '@helpers4/string';
// or, from the all-in-one package (same code, one install):
import { createSafeMatcher } from 'helpers4/string';
createSafeMatcher(pattern: MatcherPattern | readonly MatcherPattern[], options?: MatcherOptions): function | null
ParameterTypeDescription
patternMatcherPattern | readonly MatcherPattern[]A pattern, or an array of patterns and exclusions
optionsMatcherOptionsSyntax of string patterns and case sensitivity — see MatcherOptions (optional)

function | null — A function telling whether a string matches, or null for an invalid regular expression

An invalid regular expression gives null, to report it without a try.

const matches = createSafeMatcher(input);
if (!matches) console.error('Invalid filter');

For valid patterns, the result is the same predicate.

createSafeMatcher('*.fig')?.('a.fig') // => true

Options for createMatcher and createSafeMatcher.

interface MatcherOptions {
  caseSensitive?: boolean;
  extended?: boolean;
  syntax?: "auto" | "regex" | "glob";
}

One pattern accepted by createMatcher: a string (read according to MatcherOptions.syntax), a RegExp, or a predicate of your own.

type MatcherPattern = string | RegExp | ((text: string) => boolean)

View source on GitHub