You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

26 lines
717 B
JavaScript

"use strict";
const { validateArguments, required } = require("@validatem/core");
const isString = require("@validatem/is-string");
const isRegularExpression = require("@validatem/is-regular-expression");
module.exports = function matchOrError(regex, string) {
validateArguments(arguments, [
[ "regex", required, isRegularExpression ],
[ "string", required, isString ]
]);
let match = regex.exec(string);
if (match == null) {
throw new Error(`Regular expression ${regex.toString()} failed to match on string: ${string}`);
} else {
// NOTE: Follows `execall` format: https://www.npmjs.com/package/execall
return {
match: match[0],
subMatches: match.slice(1),
index: match.index
};
}
};