-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathutilities.ts
49 lines (43 loc) · 1.52 KB
/
utilities.ts
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
// https://twitter.com/mattpocockuk/status/1506607945445949446
export type LooseString<T extends string> = T | Omit<string, T>;
export const toKebabCase = (value: string): string =>
value.replace(/([a-z0–9])([A-Z])/g, "$1-$2").toLowerCase();
export function removeQuoteWrappers(value: string) {
return value.trim().replace(/^["'](.+(?=["']$))["']$/, "$1");
}
export function has(arr?: unknown[]) {
return Array.isArray(arr) && arr.length > 0;
}
export function toSentenceCase(value: string) {
return (
value
// Look for long acronyms and filter out the last letter
.replace(/([A-Z]+)([A-Z][a-z])/g, " $1 $2")
// Look for lower-case letters followed by upper-case letters
.replace(/([a-z\d])([A-Z])/g, "$1 $2")
// Look for lower-case letters followed by numbers
.replace(/([a-zA-Z])(\d)/g, "$1 $2")
.replace(/^./, (str) => str.toUpperCase())
// Remove any white space left around the word
.trim()
);
}
export function toPascalCase(value: string) {
return value
.replace(new RegExp(/[-_]+/, "g"), " ")
.replace(new RegExp(/[^\w\s]/, "g"), "")
.replace(
new RegExp(/\s+(.)(\w*)/, "g"),
($1, $2, $3) => `${$2.toUpperCase() + $3}`,
)
.replace(new RegExp(/\w/), (s) => s.toUpperCase());
}
export function toCamelCase(value: string = "") {
const arr = value.split("-");
const capital = arr.map((item, index) =>
index
? item.charAt(0).toUpperCase() + item.slice(1).toLowerCase()
: item.toLowerCase(),
);
return capital.join("");
}