Last active
September 17, 2022 16:45
-
-
Save paulohfev/bb85ee0140c4702e81de7c6ac56fbe20 to your computer and use it in GitHub Desktop.
Format string in camel case
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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