-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
39 lines (34 loc) · 1.08 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
const KEBAB_REGEX = /\p{Lu}/gu;
const REVERSE_REGEX = /-\p{Ll}/gu;
/**
* Transforms a string into kebab-case.
*
* @example
* kebabCase("helloWorld"); // "hello-world"
* kebabCase("HelloWorld"); // "-hello-world"
* kebabCase("HelloWorld", false); // "hello-world"
*
* @param {string} str The string to transform
* @param {boolean} keepLeadingDash Whether to keep the leading dash in case the string starts with an uppercase letter (default: true)
* @returns The kebab-cased string
*/
const kebabCase = (str, keepLeadingDash = true) => {
const result = str.replace(KEBAB_REGEX, (match) => `-${match.toLowerCase()}`);
if (keepLeadingDash) {
return result;
}
if (result.startsWith("-")) {
return result.slice(1);
}
};
/**
* Transforms a kebab-cased string back to the original string.
*
* @example
* kebabCase.reverse("hello-world"); // "helloWorld"
*
* @param {string} str
* @returns The original string, with the kebab-case transformation reversed
*/
kebabCase.reverse = (str) => str.replace(REVERSE_REGEX, (match) => match.slice(1).toUpperCase());
export default kebabCase;