Skip to content

Commit 1bc3131

Browse files
committed
Added string isLike function
1 parent 70747cf commit 1bc3131

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

MADE.Data.Validation/src/string/index.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,4 +19,27 @@ export function containsString(phrase: string, value: string, ignoreCase: boolea
1919
return phrase.toLowerCase().indexOf(value.toLowerCase()) !== -1;
2020
}
2121
return phrase.indexOf(value) !== -1;
22+
}
23+
24+
/**
25+
* Compares a string value against a wildcard pattern, similar to the Visual Basic like operator.
26+
* @example isLike("abc", "a?c") // returns true
27+
* @example isLike("abc", "cba*") // returns false
28+
* @param {string} value - The value to compare is like.
29+
* @param {string} likePattern - The wildcard like pattern to match on.
30+
* @return {boolean} True if the value is like the pattern; otherwise, false.
31+
*/
32+
export function isLike(value: string, likePattern: string): boolean {
33+
if (isNullOrWhiteSpace(value) || isNullOrWhiteSpace(likePattern)) {
34+
return false;
35+
}
36+
37+
// Replace wildcard characters with regular expression equivalents
38+
var escapedPattern = likePattern.replaceAll('[!', '[^')
39+
.replaceAll('?', '.')
40+
.replaceAll('*', '.*')
41+
.replaceAll('#', '\\d');
42+
43+
var regexPattern = '^' + escapedPattern + '$';
44+
return new RegExp(regexPattern).test(value);
2245
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import { isLike } from '../../src'
2+
3+
describe("when validating if a string is like", () => {
4+
test.each([
5+
["*", "abc", true],
6+
["a*", "abc", true],
7+
["a?c", "abc", true],
8+
["[a-z][a-z][a-z]", "abc", true],
9+
["###", "123", true],
10+
["###", "abc", false],
11+
["*###", "123abc", false],
12+
["[a-z][a-z][a-z]", "ABC", false],
13+
["a?c", "aba", false],
14+
])("should match pattern (pattern - %s, input - %s, expected - %s)", (pattern, input, expected) => {
15+
// Act
16+
const actual = isLike(input, pattern);
17+
18+
// Assert
19+
expect(actual).toBe(expected)
20+
});
21+
});

0 commit comments

Comments
 (0)