Skip to content

Instantly share code, notes, and snippets.

@paulohfev
Last active September 17, 2022 16:45
Show Gist options
  • Save paulohfev/bb85ee0140c4702e81de7c6ac56fbe20 to your computer and use it in GitHub Desktop.
Save paulohfev/bb85ee0140c4702e81de7c6ac56fbe20 to your computer and use it in GitHub Desktop.
Format string in camel case
const NON_SPECIAL_CHARS_REGEX = /\W+|[_]+/;
const WHITE_SPACE_REGEX = /\s+/;
const formatCamelCase = (text) => {
const formatCase = (word, index) => {
const formattedNonFirstWord = word.charAt(0).toUpperCase() + word.slice(1);
return index === 0 ? word.toLowerCase() : formattedNonFirstWord
};
return text
.replace(NON_SPECIAL_CHARS_REGEX, ' ')
.split(WHITE_SPACE_REGEX)
.map((word, index) => formatCase(word, index))
.join('')
};
// Examples
console.log(formatCamelCase('hello world')); //~> helloWorld
console.log(formatCamelCase("HELLO-World")); // ~> helloWorld
console.log(formatCamelCase("HELLO__world")); // ~> helloWorld
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment