-
-
Notifications
You must be signed in to change notification settings - Fork 25
/
index.js
59 lines (52 loc) · 1.86 KB
/
index.js
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
const handlePreserveConsecutiveUppercase = (decamelized, separator) => {
// Lowercase all single uppercase characters. As we
// want to preserve uppercase sequences, we cannot
// simply lowercase the separated string at the end.
// `data_For_USACounties` → `data_for_USACounties`
decamelized = decamelized.replace(
/((?<![\p{Uppercase_Letter}\d])[\p{Uppercase_Letter}\d](?![\p{Uppercase_Letter}\d]))/gu,
$0 => $0.toLowerCase(),
);
// Remaining uppercase sequences will be separated from lowercase sequences.
// `data_For_USACounties` → `data_for_USA_counties`
return decamelized.replace(
/(\p{Uppercase_Letter}+)(\p{Uppercase_Letter}\p{Lowercase_Letter}+)/gu,
(_, $1, $2) => $1 + separator + $2.toLowerCase(),
);
};
export default function decamelize(
text,
{
separator = '_',
preserveConsecutiveUppercase = false,
} = {},
) {
if (!(typeof text === 'string' && typeof separator === 'string')) {
throw new TypeError(
'The `text` and `separator` arguments should be of type `string`',
);
}
// Checking the second character is done later on. Therefore process shorter strings here.
if (text.length < 2) {
return preserveConsecutiveUppercase ? text : text.toLowerCase();
}
const replacement = `$1${separator}$2`;
// Split lowercase sequences followed by uppercase character.
// `dataForUSACounties` → `data_For_USACounties`
// `myURLstring → `my_URLstring`
const decamelized = text.replace(
/([\p{Lowercase_Letter}\d])(\p{Uppercase_Letter})/gu,
replacement,
);
if (preserveConsecutiveUppercase) {
return handlePreserveConsecutiveUppercase(decamelized, separator);
}
// Split multiple uppercase characters followed by one or more lowercase characters.
// `my_URLstring` → `my_ur_lstring`
return decamelized
.replace(
/(\p{Uppercase_Letter})(\p{Uppercase_Letter}\p{Lowercase_Letter}+)/gu,
replacement,
)
.toLowerCase();
}