-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathnormalCase.ts
52 lines (45 loc) · 1.25 KB
/
normalCase.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
50
51
52
import lowerCase from "./lowerCase.ts";
import nonWordRegexp from "./vendor/nonWordRegexp.ts";
import camelCaseRegexp from "./vendor/camelCaseRegexp.ts";
import camelCaseUpperRegexp from "./vendor/camelCaseUpperRegexp.ts";
/**
* Convert a `string` to normal case.
*
* Example:
*
* ```ts
* normalCase("test string");
* //=> "test string"
*
* normalCase("testString");
* //=> "test string"
*
* normalCase("Test-String");
* //=> "test string"
* ```
*/
export default function normalCase(
str: string,
locale?: string,
replacement?: string,
): string {
if (str == null) {
return "";
}
replacement = typeof replacement !== "string" ? " " : replacement;
function replace(match: string, index: number, value: string): string {
if (index === 0 || index === value.length - match.length) {
return "";
}
return replacement!;
}
str = String(str)
// Support camel case ("camelCase" -> "camel Case").
.replace(camelCaseRegexp, "$1 $2")
// Support odd camel case ("CAMELCase" -> "CAMEL Case").
.replace(camelCaseUpperRegexp, "$1 $2")
// Remove all non-word characters and replace with a single space.
.replace(nonWordRegexp, replace);
// Lower case the entire string.
return lowerCase(str, locale);
}