Skip to content

Commit 70c0e12

Browse files
committed
util: trimPrefix and trimSuffix methods
Signed-off-by: CrazyMax <crazy-max@users.noreply.github.com>
1 parent ddcd63c commit 70c0e12

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

‎__tests__/util.test.ts‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -232,6 +232,41 @@ describe('isValidRef', () => {
232232
});
233233
});
234234

235+
describe('trimPrefix', () => {
236+
test.each([
237+
['', 'abc', ''],
238+
['abc', 'a', 'bc'],
239+
['abc', 'ab', 'c'],
240+
['abc', '', 'abc'],
241+
['abc', '', 'abc'],
242+
['abc', 'd', 'abc'],
243+
['abc', 'abc', ''],
244+
['abc', 'abcd', 'abc'],
245+
['abcdabc', 'abc', 'dabc'],
246+
['abcabc', 'abc', 'abc'],
247+
['abcdabc', 'd', 'abcdabc']
248+
])('given %p', async (str, prefix, expected) => {
249+
expect(Util.trimPrefix(str, prefix)).toEqual(expected);
250+
});
251+
});
252+
253+
describe('trimSuffix', () => {
254+
test.each([
255+
['', 'abc', ''],
256+
['abc', 'c', 'ab'],
257+
['abc', '', 'abc'],
258+
['abc', 'bc', 'a'],
259+
['abc', 'abc', ''],
260+
['abc', 'abcd', 'abc'],
261+
['abc', 'aabc', 'abc'],
262+
['abcdabc', 'abc', 'abcd'],
263+
['abcabc', 'abc', 'abc'],
264+
['abcdabc', 'd', 'abcdabc']
265+
])('given %p', async (str, suffix, expected) => {
266+
expect(Util.trimSuffix(str, suffix)).toEqual(expected);
267+
});
268+
});
269+
235270
// See: https://github.com/actions/toolkit/blob/a1b068ec31a042ff1e10a522d8fdf0b8869d53ca/packages/core/src/core.ts#L89
236271
function getInputName(name: string): string {
237272
return `INPUT_${name.replace(/ /g, '_').toUpperCase()}`;

‎src/util.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,4 +111,26 @@ export class Util {
111111
}
112112
return false;
113113
}
114+
115+
public static trimPrefix(str: string, suffix: string): string {
116+
if (!str || !suffix) {
117+
return str;
118+
}
119+
const index = str.indexOf(suffix);
120+
if (index !== 0) {
121+
return str;
122+
}
123+
return str.substring(suffix.length);
124+
}
125+
126+
public static trimSuffix(str: string, suffix: string): string {
127+
if (!str || !suffix) {
128+
return str;
129+
}
130+
const index = str.lastIndexOf(suffix);
131+
if (index === -1 || index + suffix.length !== str.length) {
132+
return str;
133+
}
134+
return str.substring(0, index);
135+
}
114136
}

0 commit comments

Comments
 (0)