-
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathtoSnakeCase.ts
More file actions
74 lines (68 loc) · 2.14 KB
/
toSnakeCase.ts
File metadata and controls
74 lines (68 loc) · 2.14 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
import { requireNonEmptyString } from "./requireNonEmptyString";
interface ToSnakeCaseOptions {
clean?: boolean;
trim?: boolean;
}
/**
* Converts a string to `snake_case` format.
*
* `snake_case` is a naming convention where words are separated by underscores (`_`),
* and all letters are in lowercase.
*
* This function handles spaces, hyphens, and camelCase transitions by inserting underscores.
* It also normalizes underscores by removing leading/trailing ones and collapsing multiples.
*
* @example (Default Behavior - keeps other characters)
* ```javascript
* const text = "Hello world! How are you?";
* const result = toSnakeCase(text);
*
* console.log(result); // hello_world!_how_are_you?
* ```
*
* @example (Strict Cleaning - removes other characters)
* ```javascript
* const text = "Hello world! How are you?";
* const result = toSnakeCase(text, { clean: true });
*
* console.log(result); // hello_world_how_are_you
* ```
*
* @example (With Input Trimming)
* ```javascript
* const textWithWhitespace = " Hello world ";
* const resultTrimmed = toSnakeCase(textWithWhitespace, { trimInput: true });
*
* console.log(resultTrimmed); // hello_world
* ```
*
* @param {string} value - The input string to convert.
* @param {ToSnakeCaseOptions} [options] - Optional configuration options.
* @returns {string} The string converted to snake_case.
* @throws {@link EmptyStringException}
* @see {@link toCamelCase}
* @see {@link toKebabCase}
* @see {@link toLowerCase}
* @see {@link toProperCase}
* @see {@link toUpperCase}
* @since 1.0.0
* @version 1.0.0
*/
export function toSnakeCase(value: string, options?: ToSnakeCaseOptions): string {
const effectiveOptions: Required<ToSnakeCaseOptions> = {
clean: false,
trim: false,
...(options || {})
};
let result = requireNonEmptyString(value)
.replace(/[\s-]/g, "_")
.replace(/([a-z])([A-Z])/g, "$1_$2")
.toLowerCase();
if (effectiveOptions.clean !== false) {
result = result.replace(/[^a-zA-Z0-9_]/g, "");
}
if (effectiveOptions.trim === true) {
result = result.trim().replace(/_+/g, "_");
}
return result;
}