|
1
|
/** |
|
2
|
* Matches kebab-case: lowercase letters, digits, and hyphens; must start |
|
3
|
* with a letter and cannot end with or contain consecutive hyphens. |
|
4
|
*/ |
|
5
|
export const KEBAB_CASE_RE = /^[a-z][a-z0-9]*(-[a-z0-9]+)*$/ |
|
6
|
|
|
7
|
/** |
|
8
|
* Matches snake_case: lowercase letters, digits, and underscores; must start |
|
9
|
* with a letter. |
|
10
|
*/ |
|
11
|
export const SNAKE_CASE_RE = /^[a-z][a-z0-9_]*$/ |
|
12
|
|
|
13
|
/** |
|
14
|
* Converts an identifier to kebab-case. Handles camelCase, PascalCase, |
|
15
|
* snake_case, whitespace-separated, and consecutive-uppercase runs |
|
16
|
* (`myXMLParser` → `my-xml-parser`). |
|
17
|
*/ |
|
18
|
export const toKebab = (input: string): string => |
|
19
|
input |
|
20
|
.replace(/[_\s]+/g, "-") |
|
21
|
.replace(/([a-z0-9])([A-Z])/g, "$1-$2") |
|
22
|
.replace(/([A-Z]+)([A-Z][a-z])/g, "$1-$2") |
|
23
|
.toLowerCase() |
|
24
|
|
|
25
|
/** |
|
26
|
* Converts an identifier to snake_case. Handles camelCase, PascalCase, |
|
27
|
* kebab-case, whitespace-separated, dot-separated, and consecutive-uppercase |
|
28
|
* runs (`myXMLParser` → `my_xml_parser`). Any non-alphanumeric character |
|
29
|
* becomes a separator; runs of underscores collapse; leading/trailing |
|
30
|
* underscores are trimmed. |
|
31
|
*/ |
|
32
|
export const toSnake = (input: string): string => |
|
33
|
input |
|
34
|
.replace(/([a-z0-9])([A-Z])/g, "$1_$2") |
|
35
|
.replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2") |
|
36
|
.toLowerCase() |
|
37
|
.replace(/[^a-z0-9]+/g, "_") |
|
38
|
.replace(/^_+|_+$/g, "") |