Skip to content

Instantly share code, notes, and snippets.

@OrderAndCh4oS
Last active July 19, 2019 08:36
Show Gist options
  • Save OrderAndCh4oS/9df7d82bccdbb9f57ebd8b47221014a4 to your computer and use it in GitHub Desktop.
Save OrderAndCh4oS/9df7d82bccdbb9f57ebd8b47221014a4 to your computer and use it in GitHub Desktop.
Switch String Case. Coverts camelCase or PascalCase to kebab-case or snake_case or any delimited string and vice versa,
const camelCaseToDelimitedString = (string, delimiter = '-') =>
string.replace(/([a-z0-9]|(?<!^)(?=[A-Z]))([A-Z])/g, '$1'+delimiter+'$2').toLowerCase();
const delimitedStringToCamelCase = (string, delimiter = '-') =>
string.replace(new RegExp(delimiter + '([a-z])', 'g'), (m, c) => c.toUpperCase());
@OrderAndCh4oS
Copy link
Author

/**
 * Examples
 */
console.log(camelCaseToDelimitedString('helloWorld'));
console.log(camelCaseToDelimitedString('helloWorld', '_'));
console.log(camelCaseToDelimitedString('HelloWorld'));
console.log(camelCaseToDelimitedString('HelloWorld', '_'));
console.log(delimitedStringToCamelCase('hello-world'));
console.log(delimitedStringToCamelCase('hello, world', ', '));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment