Skip to content

Instantly share code, notes, and snippets.

@usrbowe
Last active June 15, 2018 15:16
Show Gist options
  • Save usrbowe/69bf2dce2c00390c7e056f9595c159bc to your computer and use it in GitHub Desktop.
Save usrbowe/69bf2dce2c00390c7e056f9595c159bc to your computer and use it in GitHub Desktop.
Camelize string in Javascript / ES6 💪
/* Transform dasherized, underscored string to camelCase */
const cameliseMe = (str, separator = "-") => {
const splitted = str.split(separator);
if (splitted.length === 1) return str;
return splitted.reduce(
(acc, [up, ...rest]) => `${acc}${up.toUpperCase() + rest.join("")}`
);
};
/* Basic example
cameliseMe('this-is-easy-dasherized-string');
// OUTPUT:
'thisIsEasyDasherizedString'
*/
@usrbowe
Copy link
Author

usrbowe commented Jun 15, 2018

Also possible to add sanitize option which would clean any white-spaces, and mixed lower/upper case of characters.
Like this: ThIs- is- CompleteLy-WroNG

const cameliseMe = (str, separator = "-", sanitize = false) => {
  const newStr = sanitize ? str.toLowerCase().replace(" ", "").trim() : str;
  const splitted = newStr.split(separator);
  if (splitted.length === 1) return newStr;
  return splitted.reduce(
    (acc, [up, ...rest]) => `${acc}${up.toUpperCase() + rest.join("")}`
  );
};
// Example: cameliseMe('ThIs- is- CompleteLy-WroNG', undefined, true) --> 'thisIsCompletelyWrong'

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