Skip to content

Instantly share code, notes, and snippets.

@jbreckmckye
Last active January 11, 2024 11:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jbreckmckye/10902046e1848a608a21f430affabfb8 to your computer and use it in GitHub Desktop.
Save jbreckmckye/10902046e1848a608a21f430affabfb8 to your computer and use it in GitHub Desktop.
Wildcard matching string function
"use strict";
function matchWildcard(match, str) {
match = match.replace(/\*+/, '*');
let sn = 0;
let m, s;
for (let mn = 0; mn < match.length; mn++, sn++) {
m = match[mn];
s = str[sn];
if (m === '*') {
// Bail out at end of match
if (mn == match.length - 1) {
return [sn <= str.length - 1, '* end']; // ending * matches 1..n remaining in str
}
// Ignore 1..Inf chars until next char = next match
let nextS = str[sn + 1];
let nextM = match[mn + 1];
while (nextS !== nextM && nextM !== '?' && sn < str.length) {
sn++;
nextS = str[sn + 1];
}
continue;
}
if (m === '?') {
continue; // Ignore 1 character
}
if (m !== s) {
return [false, `mismatch ${m} ${s}`];
}
}
if (sn !== str.length) {
return [false, `bad len ${sn} ${str.length}`]; // After completing the match, there are more chars
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment