Last active
September 27, 2023 09:33
-
-
Save blaskovicz/ac9444c5efd2869ed259fcea0e06e3e6 to your computer and use it in GitHub Desktop.
trimPrefix() and trimSuffix() in TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {} from 'jasmine'; | |
import {trimSuffix, trimPrefix} from './string'; | |
describe('string utils', () => { | |
describe('trimSuffix', () => { | |
for (const [from, trim, to] of [ | |
[null, 'abc', null], | |
['abc', 'c', 'ab'], | |
['abc', '', 'abc'], | |
['abc', null, 'abc'], | |
['abc', 'bc', 'a'], | |
['abc', 'abc', '' ], | |
['abc', 'abcd', 'abc'], | |
['abc', 'aabc', 'abc'], | |
['abcdabc', 'abc', 'abcd'], | |
['abcabc', 'abc', 'abc'], | |
['abcdabc', 'd', 'abcdabc'], | |
]) { | |
it(`(from=${from}, trim=${trim}) => to=${to}`, () => { | |
expect(trimSuffix(from,trim)).toEqual(to); | |
}); | |
} | |
}); | |
describe('trimPrefix', () => { | |
for (const [from, trim, to] of [ | |
[null, 'abc', null], | |
['abc', 'a', 'bc'], | |
['abc', 'ab', 'c'], | |
['abc', '', 'abc'], | |
['abc', null, 'abc'], | |
['abc', 'd', 'abc'], | |
['abc', 'abc', ''], | |
['abc', 'abcd', 'abc'], | |
['abcdabc', 'abc', 'dabc'], | |
['abcabc', 'abc', 'abc'], | |
['abcdabc', 'd', 'abcdabc'], | |
]) { | |
it(`(from=${from}, trim=${trim}) => to=${to}`, () => { | |
expect(trimPrefix(from,trim)).toEqual(to); | |
}); | |
} | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// trimSuffix('abc', 'c') -> 'ab' | |
export function trimSuffix(toTrim: string, trim: string): string { | |
if (!toTrim || !trim) { | |
return toTrim; | |
} | |
const index = toTrim.lastIndexOf(trim); | |
if (index === -1 || (index + trim.length) !== toTrim.length) { | |
return toTrim; | |
} | |
return toTrim.substring(0, index); | |
} | |
// trimPrefix('abc', 'ab') -> 'c' | |
export function trimPrefix(toTrim: string, trim: string): string { | |
if (!toTrim || !trim) { | |
return toTrim; | |
} | |
const index = toTrim.indexOf(trim); | |
if (index !== 0) { | |
return toTrim; | |
} | |
return toTrim.substring(trim.length); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
💻 Edit or ⏯️ run this Gist on the www.CarlyZach.com code playground 💻