Skip to content

Instantly share code, notes, and snippets.

@azinasili
Last active April 12, 2019 17:56
Show Gist options
  • Save azinasili/811a8d52415e7ff0bdd0eeec29dbfd3e to your computer and use it in GitHub Desktop.
Save azinasili/811a8d52415e7ff0bdd0eeec29dbfd3e to your computer and use it in GitHub Desktop.
Takes a string and converts to camelCase
/**
* Convert string to camelCase.
* Function will remove `,`, `_`, `-`, and `' '` from string.
*
* Note: Function does not strip numeric characters.
* A string like `hello 1world` would return `hello1world`
*
* @example
* camelCase('hello world') // returns 'helloWorld'
*
* @example
* camelCase('hello_world') // returns 'helloWorld'
*
* @example
* camelCase('hello-world') // returns 'helloWorld'
*
* @example
* camelCase('hello,world') // returns 'helloWorld'
*
* @example
* camelCase('__--HeLlO wOrLd--__') // returns 'helloWorld'
*
* @param {string} string - String to convert
* @returns {string}
*/
function camelCase(string) {
const strArry = string.split(/[ ,_-]+/).filter(Boolean);
const capitalize = strArry.map((str, index) => {
if (index === 0) return str.toLowerCase();
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
});
return capitalize.join('');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment