Skip to content

Instantly share code, notes, and snippets.

@blaskovicz
Last active September 27, 2023 09:33
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 blaskovicz/ac9444c5efd2869ed259fcea0e06e3e6 to your computer and use it in GitHub Desktop.
Save blaskovicz/ac9444c5efd2869ed259fcea0e06e3e6 to your computer and use it in GitHub Desktop.
trimPrefix() and trimSuffix() in TypeScript
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);
});
}
});
});
// 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);
}
@blaskovicz
Copy link
Author

@blaskovicz
Copy link
Author

@vanduc1102
Copy link

thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment