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.0.0] - 2025-07-29

### Added
Expand Down
31 changes: 30 additions & 1 deletion src/lib/string.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { isNullOrEmpty, isNullOrWhitespace, capitalize, uncapitalize, truncate } from "./string";
import { isNullOrEmpty, isNullOrWhitespace, capitalize, uncapitalize, truncate, splitLine } from "./string";

describe("string tests", () => {
test.each([
Expand Down Expand Up @@ -120,4 +120,33 @@ describe("string tests", () => {
])("truncate without suffix parameter", (value, maxLength, expected) => {
expect(truncate(value, maxLength)).toBe(expected);
});

test.each([["hello world", ["hello world"]]])("splitLine with single line", (str, expected) => {
Comment thread
drebrez marked this conversation as resolved.
Outdated
expect(splitLine(str)).toStrictEqual(expected);
});

test.each([
["hello world", ["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", (str, expected) => {
expect(splitLine(str)).toStrictEqual(expected);
});

test.each([
["", []],
[null as unknown as string, []],
[undefined as unknown as string, []],
])("splitLine with empty strings", (str, expected) => {
expect(splitLine(str)).toStrictEqual(expected);
});

test.each([
[null as unknown as string, []],
[undefined as unknown as string, []],
["hello world\n", ["hello world"]],
])("splitLine with the option to remove empty entries", (str, expected) => {
expect(splitLine(str, true)).toEqual(expected);
});
});
17 changes: 17 additions & 0 deletions src/lib/string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,3 +64,20 @@ 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 [];
}

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