Description
We want to join the word tokens of a phrase together, by capitalized each term’s first word.
End Goal
function camelize(str) {
return str
.replace(/\s(.)/g, function($1) { return $1.toUpperCase(); })
.replace(/\s/g, '')
.replace(/\-(.)/g, function($1) { return $1.toUpperCase(); })
.replace(/\-/g, '')
.replace(/^(.)/, function($1) { return $1.toLowerCase(); });
}
Step by step
- Capitalize each first letter of the word that follows a space
.replace(/s(.)/g, function($1) { return $1.toUpperCase(); })
- Remove all spaces
.replace(/\s/g, '')
- Capitalize each first letter of the word that follows a dash
.replace(/\-(.)/g, function($1) { return $1.toUpperCase(); })
- Remove all dashes
.replace(/\-/g, '')
- Make sure the first is lowercased
.replace(/^(.)/, function($1) { return $1.toLowerCase(); });
Now you can do this!
Resources:
use cases
- Turn user input into bot commands:
camelize(userInput) === systemCommand