Skip to content

Instantly share code, notes, and snippets.

@rebolyte
Created February 13, 2017 16:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rebolyte/01fde7705a891ca1df8e4d2a448d2def to your computer and use it in GitHub Desktop.
Save rebolyte/01fde7705a891ca1df8e4d2a448d2def to your computer and use it in GitHub Desktop.
Change a string from camelCase to kebab-case or snake_case and vice versa
'use strict';
let DASH_LOWERCASE_REGEX = /-([a-z])/g;
let UNDERSCORE_LOWERCASE_REGEX = /_([a-z])/g;
let UPPERCASE_REGEX = /([A-Z])/g;
// func argument to .replace receives:
// 1) the matched substring
// 2) nth parenthesized substr match (i.e. if the pattern has any `()` group matches,
// those will be passed as the next args)
// 3) numeric index of the match in the whole string
// 4) full original string
// kebabToCamel('class-name-here');
// match: -n letter: n
// match: -h letter: h
function kebabToCamel(name) {
return name.replace(DASH_LOWERCASE_REGEX, (match, letter) => letter.toUpperCase());
}
function snakeToCamel(name) {
return name.replace(UNDERSCORE_LOWERCASE_REGEX, (match, letter) => letter.toUpperCase());
}
function camelToSnake(name) {
return name.replace(UPPERCASE_REGEX, match => '_' + match.toLowerCase());
}
function camelToKebab(name) {
return name.replace(UPPERCASE_REGEX, match => '-' + match.toLowerCase());
}
let out1 = snakeToCamel('table_name_here');
let out2 = camelToSnake('thisAttrName');
console.log('snakeToCamel:', out1); // -> 'tableNameHere'
console.log('camelToSnake:', out2); // -> 'this_attr_name'
@rebolyte
Copy link
Author

rebolyte commented Feb 13, 2017

Or, you know, use lodash's _.camelCase, _.kebabCase, and _.snakeCase.

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