-
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathtoCamelCase.ts
More file actions
65 lines (59 loc) · 1.88 KB
/
toCamelCase.ts
File metadata and controls
65 lines (59 loc) · 1.88 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
import { requireNonEmptyString } from "./requireNonEmptyString";
interface ToCamelCaseOptions {
clean?: boolean;
firstWordToLowerCase?: boolean;
}
/**
* Converts a string to `camelCase` format.
*
* `camelCase` is a naming convention where the first letter of each word (except
* potentially the very first word) is capitalized, and all spaces, hyphens,
* and underscores are removed.
*
* By default, the resulting string's first letter is converted to lowercase.
*
* @example (Default Behavior)
* ```javascript
* const text = "Hello world! How are you?";
* const result = toCamelCase(text);
*
* console.log(result); // helloWorldHowAreYou
* ```
*
* @example (Keeping first letter uppercase)
* ```javascript
* const text = "Hello world!";
* const result = toCamelCase(text, { firstWordToLowerCase: false });
*
* console.log(result); // HelloWorld
* ```
*
* @param {string} value - The input string to convert.
* @param {ToCamelCaseOptions} [options] - Optional configuration options.
* @returns {string} The string converted to camelCase.
* @throws {@link EmptyStringException}
* @see {@link toKebabCase}
* @see {@link toLowerCase}
* @see {@link toProperCase}
* @see {@link toSnakeCase}
* @see {@link toUpperCase}
* @since 1.0.0
* @version 1.0.0
*/
export function toCamelCase(value: string, options: ToCamelCaseOptions = {}): string {
const effectiveOptions: Required<ToCamelCaseOptions> = {
clean: true,
firstWordToLowerCase: true,
...options
};
let result = requireNonEmptyString(value)
.replace(/\b\w+\b/g, (match) => match.charAt(0).toUpperCase() + match.slice(1).toLowerCase())
.replace(/[\s-_]+/g, "");
if (effectiveOptions.clean) {
result = result.replace(/[^a-zA-Z0-9]/g, "");
}
if (effectiveOptions.firstWordToLowerCase) {
result = result.charAt(0).toLowerCase() + result.slice(1);
}
return result;
}