-
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathtoProperCase.ts
More file actions
58 lines (53 loc) · 1.79 KB
/
toProperCase.ts
File metadata and controls
58 lines (53 loc) · 1.79 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
import { requireNonEmptyString } from "./requireNonEmptyString";
interface ToProperCaseOptions {
trim?: boolean;
}
/**
* Returns a new string with the first letter of each word capitalized and the rest lowercased (Proper Case / Title Case).
*
* This function processes the input string to capitalize the first letter of every
* word and convert the remaining letters of each word to lowercase.
* Optionally, it can also normalize whitespace.
*
* @example (Default Behavior)
* ```javascript
* const text = "hello WORLD! how are you?";
* const result = toProperCase(text);
*
* console.log(result); // Hello World! How Are You?
* ```
*
* @example (With Trimming)
* ```javascript
* const textWithWhitespace = " hello world! how are you? ";
* const trimmedResult = toProperCase(textWithWhitespace, { trim: true });
*
* console.log(trimmedResult); // Hello World! How Are You?
* ```
*
* @param {string} value - The input string to convert.
* @param {ToProperCaseOptions} [options] - Optional configuration options.
* @returns {string} The string converted to proper case, with optional whitespace normalization.
* @throws {@link EmptyStringException}
* @see {@link toCamelCase}
* @see {@link toKebabCase}
* @see {@link toLowerCase}
* @see {@link toSnakeCase}
* @see {@link toUpperCase}
* @since 1.0.0
* @version 1.0.0
*/
export function toProperCase(value: string, options: ToProperCaseOptions = {}): string {
const effectiveOptions: Required<ToProperCaseOptions> = {
trim: false,
...options
};
let result = requireNonEmptyString(value).replace(
/\b\w+\b/g,
(match) => match.charAt(0).toUpperCase() + match.slice(1).toLowerCase()
);
if (effectiveOptions.trim === true) {
result = result.trim().replace(/\s+/g, " ");
}
return result;
}