UNPKG

@monstermann/fn

Version:

A utility library for TypeScript.

27 lines (25 loc) 914 B
import { FnError } from "../function/FnError.js"; import { dfdlT } from "@monstermann/dfdl"; //#region src/string/matchOrThrow.ts /** * `matchOrThrow(target, source)` * * Returns the result of matching `target` string against `source` string or regular expression, or throws an error if no match is found. * * ```ts * matchOrThrow("hello world", "world"); // ["world", index: 6, input: "hello world", groups: undefined] * matchOrThrow("hello world", /\d+/); // throws FnError * ``` * * ```ts * pipe("hello world", matchOrThrow("world")); // ["world", index: 6, input: "hello world", groups: undefined] * pipe("hello world", matchOrThrow(/\d+/)); // throws FnError * ``` */ const matchOrThrow = dfdlT((target, source) => { const match = target.match(source); if (match) return match; throw new FnError("String.matchOrThrow: Value did not match.", [target, source]); }, 2); //#endregion export { matchOrThrow };