Reputation: 723
I'm trying to create a function that returns a string in camel case capitalizing each letter where there is a hyphen.
i.e. "this-should-be-camel-case"
would return "thisShouldBeCamelCase"
.
I've changed to first letter of each word to capital and removed to hyphen but can't get the completed sentence to return. I've tried playing with substr
and substring
to no avail, not sure if they're what I want to be using for the task.
What should I be using to return the sentence in camel case ? How do I do this ? Thanks
function camelCaseIt(str) {
for(var i = 0; i < str.length; i++) {
if(str[i] == '-') {
var chgLtr = str[i] = '';
var uprCase = str[i+1].toUpperCase();
}
}
return str;
}
alert(camelCaseIt('this-should-be-camel-cased'));
Upvotes: 1
Views: 114
Reputation: 5056
Indexing the characters of a string as though it's a character array may not work in all browsers (it's nonstandard behavior prior to EMCAScript 5). While it's correct for browsers compatible with the newest JS standard, you shouldn't use that syntax if you want to support older browsers. (And even in EMCAScript 5, you can't do for example str[i] = ''
.)
function camelCaseIt(str) {
// create an array ['this', 'should', 'be', 'camel', 'cased']
var parts = str.split('-');
// start at i = 1 to skip the first word
for (var i = 1; i < parts.length; i++) {
// create an array ['s', 'h', 'o', 'u', 'l', 'd']
var ltrs = parts[i].split('');
// ltrs is now ['S', 'h', 'o', 'u', 'l', 'd']
ltrs[0] = ltrs[0].toUpperCase();
// parts is now ['this', 'Should', 'Be', 'Camel', 'Cased']
parts[i] = ltrs.join('');
}
// return thisShouldBeCamelCased
return parts.join('');
}
Upvotes: 1
Reputation: 38436
In your function, you're returning the original (unmodified string). Instead, you should be building a separate (new) string and returning that:
function camelCaseIt(str) {
var modifiedString = '';
for(var i = 0; i < str.length; i++) {
if(str.charAt(i) == '-') {
// hyphen; if there is another character, upper-case it and append
if ((i + 1) < str.length) {
modifiedString = str.charAt(i + 1).toUpperCase();
}
} else {
// normal character; append it as-is
modifiedString += str.charAt(i);
}
}
return modifiedString;
}
However, you should be able to accomplish the same thing with a simple regex:
str = str.replace(/-([a-z])/g, function (match) {
return match[1].toUpperCase();
});
Upvotes: 1
Reputation: 12577
This can be accomplished fairly simply with a regular expression:
function camelCaseIt(str) {
return str.replace(/-([a-z])?/g, function(v) { return (v.length > 1 ? v[1].toUpperCase() : ''); });
}
Upvotes: 3