Skip to content
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added

- `splitLine` string utility function

## [2.1.0] - 2025-09-03

### Added
Expand Down
21 changes: 21 additions & 0 deletions src/lib/string.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
capitalize,
uncapitalize,
truncate,
splitLine,
isValidSwissIbanNumber,
isValidSwissSocialSecurityNumber,
} from "./string";
Expand Down Expand Up @@ -129,6 +130,26 @@ describe("string tests", () => {
expect(truncate(value, maxLength)).toBe(expected);
});

test.each([
["", []],
["hello world\n", ["hello world", ""]],
])("splitLine without the parameter to remove the empty entries", (str, expected) => {
expect(splitLine(str)).toEqual(expected);
});

test.each([
["", []],
[null as unknown as string, []],
[undefined as unknown as string, []],
["hello world", ["hello world"]],
["hello world\n", ["hello world"]],
["hello world\nhello world\nhello world", ["hello world", "hello world", "hello world"]],
["hello world\rhello world\rhello world", ["hello world", "hello world", "hello world"]],
["hello world\r\nhello world\r\nhello world", ["hello world", "hello world", "hello world"]],
Comment thread
drebrez marked this conversation as resolved.
Outdated
])("splitLine with the parameter to remove empty entries", (str, expected) => {
Comment thread
drebrez marked this conversation as resolved.
Outdated
expect(splitLine(str, true)).toEqual(expected);
});

test.each([
[null as unknown as string, false],
[undefined as unknown as string, false],
Expand Down
15 changes: 15 additions & 0 deletions src/lib/string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,21 @@ export function truncate(value: string | undefined, maxLength: number, suffix =
return `${value.slice(0, maxLength)}${suffix}`;
}

/**
* Splits the string at line breaks
* @param str the string to split
* @param removeEmptyEntries the option to remove empty entries
* @returns the individual lines as an array
*/
export function splitLine(str: string, removeEmptyEntries: boolean = false): string[] {
Comment thread
drebrez marked this conversation as resolved.
Outdated
if (isNullOrEmpty(str)) {
return [];
}

const splitted = str.split(/\r\n|\r|\n/);
return removeEmptyEntries ? splitted.filter((line) => !isNullOrWhitespace(line)) : splitted;
Comment thread
drebrez marked this conversation as resolved.
Outdated
}

/**
* Checks if the provided string is a valid swiss IBAN number
* @param ibanNumber The provided IBAN number to check
Expand Down
Loading