forked from neolution-ch/javascript-utils
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring.ts
More file actions
75 lines (65 loc) · 2.16 KB
/
string.ts
File metadata and controls
75 lines (65 loc) · 2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/**
* Indicates whether a specified string is null/undefined or empty
* @param value The string to test
* @returns true if the value parameter is null/undefined or empty
*/
export function isNullOrEmpty(value?: string): boolean {
if (!value || typeof value !== "string") {
return true;
}
return value.length === 0;
}
/**
* Indicates whether a specified string is null/undefined, empty, or consists only of white-space characters
* @param value The string to test
* @returns true if the value parameter is null/undefined, Empty, or if value consists exclusively of white-space characters
*/
export function isNullOrWhitespace(value?: string): boolean {
return isNullOrEmpty(value) || (value as string).trim().length === 0;
}
/**
* Capitalize the string
* @param value The string to capitalize
* @returns The capitalized string
*/
export function capitalize(value?: string): string | undefined {
if (!value || isNullOrWhitespace(value)) {
return value;
}
return value.charAt(0).toUpperCase() + value.slice(1);
}
/**
* Uncapitalize the string
* @param value The string to uncapitalize
* @returns The uncapitalized string
*/
export function uncapitalize(value?: string): string | undefined {
if (!value || isNullOrWhitespace(value)) {
return value;
}
return value.charAt(0).toLowerCase() + value.slice(1);
}
/**
* Truncates a string to a maximum length, adding a suffix if truncated
* @param value The string to truncate
* @param maxLength The maximum length of the resulting string
* @param suffix The suffix to append if truncated (default: "")
* @returns The truncated string
*/
export function truncate(value: string | undefined, maxLength: number, suffix = ""): string | undefined {
if (!value || isNullOrWhitespace(value)) {
return value;
}
if (value.length <= maxLength) {
return value;
}
return `${value.slice(0, maxLength)}${suffix}`;
}
/**
* Splits the string at line breaks
* @param str the string to split
* @returns the individual lines as an array
*/
export function splitLine(str: string): string[] {
return str.split(/\r\n|\r|\n/);
}