Skip to content

Instantly share code, notes, and snippets.

@mmyoji
Last active July 5, 2023 12:23
Show Gist options
  • Save mmyoji/36b7a4d8a807c1aaf065 to your computer and use it in GitHub Desktop.
Save mmyoji/36b7a4d8a807c1aaf065 to your computer and use it in GitHub Desktop.
Replace camelCaseString with dashed-string
/**
* @example
* ```ts
* hyphenize("someCamelCaseString");
* //=> "some-camel-case-string"
*
* hyphenize("ABigHouse");
* //=> "a-big-house"
* ```
*/
export function hyphenize(str: string): string {
const chars = str.match(/[A-Z]/g);
if (!chars) return str;
let ret = str;
for (const val of chars) {
ret = ret.replace(val, "-" + val.toLowerCase());
}
if (ret.startsWith("-")) {
return ret.slice(1, ret.length);
}
return ret;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment