I've seen plenty of easy ways to convert camelCaseNames
to camel Case Names
, etc. but none on how to convert Sentence case names
to sentenceCaseNames
. Is there any easy way to do this in JS?
Asked
Active
Viewed 1.3k times
-3

Ky -
- 30,724
- 51
- 192
- 308
-
Sure, toLowerCase, split on space, concatenate after uppercasing the first letter. – Kevin B Aug 01 '14 at 17:08
-
1What have you tried? Split on space, then change lettering, then concatenate. – Ivan Aug 01 '14 at 17:08
-
3I'm not sure my browser can keep up with the up and down votes! – Tom Fenech Aug 01 '14 at 17:08
-
@showdev no, that's the other way around – Ky - Aug 01 '14 at 18:57
-
@Supuhstar Am I missing something? You want `Sentence case names to sentenceCaseNames`, right? [This answer](http://stackoverflow.com/questions/2970525/javascript-regex-camel-case-sentence-case#answer-2970667) does `Equipment Class Name to equipmentClassName`. – showdev Aug 01 '14 at 19:02
-
1It is a duplicate, despite its misleading title. The two answers have the same result: http://jsfiddle.net/Uz7Te/ – showdev Aug 01 '14 at 19:10
-
@showdev thanks... gawsh this isn't the first time I've been fooled by a terrible title either :/ – Ky - Aug 01 '14 at 19:37
-
2I know, same here. Also, I don't mean to diminish ShaneQful's answer -- it works well and is arguably cleaner code. – showdev Aug 01 '14 at 19:39
1 Answers
13
This should do the trick :
function toCamelCase(sentenceCase) {
var out = "";
sentenceCase.split(" ").forEach(function (el, idx) {
var add = el.toLowerCase();
out += (idx === 0 ? add : add[0].toUpperCase() + add.slice(1));
});
return out;
}
Explanation:
sentenceCase.split(" ")
creates and array out of the sentence eg. ["Sentence", "case", "names"]forEach
loops through each variable in the arrayinside the loop each string is lowercased, then the first letter is uppercased(apart for the first string) and the new string is appended to the
out
variable which is what the function will eventually return as the result.

ShaneQful
- 2,140
- 1
- 16
- 22