match()
seems to check whether part of a string matches a regex, not the whole thing. Does it solve the problem? Can I adapt it to solve the problem? How?
Yes, you can. ^
and $
are not needed if you so choose.
The idea is simple: .match()
returns a "match" array. If the first element (i.e. the whole match, or $0
) equals to the string, then we have a full match.
function fullMatch(string, regex) {
const match = string.match(regex);
return match?.[0] === string;
}
Try it:
console.config({ maximize: true });
function fullMatch(string, regex) {
const match = string.match(regex);
console.log(match);
return match?.[0] === string;
}
const string = 'f00bar';
const testcases = [
/\d+c?ba/, // false
/f\d+\w+/, // true
/[0a-z]+/g // false
];
testcases.forEach(
regex => console.log(fullMatch(string, regex))
);
<script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
Note that this does not work with g
regexes, as this flag causes .match()
to always return a normal array if there is at least one match.
You can, however, use RegExp#exec()
instead:
function fullMatch(string, regex) {
const match = regex.exec(regex);
return match?.[0] === string;
}
Try it:
console.config({ maximize: true });
function fullMatch(string, regex) {
const match = regex.exec(string);
console.log(match);
return match?.[0] === string;
}
const string = 'f00bar';
const testcases = [
/\d+c?ba/, // false
/f\d+\w+/, // true
/[0a-z]+/g // true
];
testcases.forEach(
regex => console.log(fullMatch(string, regex))
);
<script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
One-liner:
const fullMatch = (string, array) => regex.exec(string)?.[0] === string;