Skip to content

Instantly share code, notes, and snippets.

@johncaruso
Forked from rebolyte/case-convert.js
Created June 18, 2018 23:21
Show Gist options
  • Select an option

  • Save johncaruso/c730973e95d125cbfa1f2918fd9e0530 to your computer and use it in GitHub Desktop.

Select an option

Save johncaruso/c730973e95d125cbfa1f2918fd9e0530 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'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment