hey guy can anybody help me to fix my code so that it does the task shown in the text,
function tad(strg) {
var char = strg.split('-')
for (var i = 1; i < char.length; i++) {
return char[i].charAt(0).toUpperCase() + char[i].slice(1)
}
}
camelize("background-color") == 'backgroundColor'
camelize("list-style-image") == 'listStyleImage'
Assuming you want to replace all word combinations that have a hyphen in it to a camel cased word. You can use a regex with String.replace
with a callback function that capitalizes all words after the hyphen.
function camelize (strg) {
return strg.replace(/-(\w)/g, function (match) {
return match[1].toUpperCase();
});
}
camelize("background-color");
// backgroundColor
camelize("z-index");
// zIndex
camelize("list-style-image");
// listStyleImage
Change your function like bellow
function tad(strg) {
var char = strg.split('-')
for (var i = 1; i < char.length; i++) {
char[i] = char[i].charAt(0).toUpperCase() + char[i].slice(1)
}
return char.join('');
}
You are returning before the loop completes its iterations. The best thing here would be to use Array.prototype.reduce
like this
function tad(strg) {
return strg.split('-').reduce(function(result, currentStr) {
return result + currentStr.charAt(0).toUpperCase() + currentStr.slice(1);
}, "");
}
console.log(tad("background-color") === "backgroundColor");
# true
console.log(tad("list-style-image") === "listStyleImage");
# true
You return
from the whole function in the first iteration of that loop. Instead, you want to do that for every part, and the join the parts together:
function camelize(string) {
return string.split('-').map(function(part, i) {
return i ? part.charAt(0).toUpperCase() + part.slice(1) : part;
}).join("");
}
// or
function camelize(string) {
return string.split('-').reduce(function(m, part) {
return m + part.charAt(0).toUpperCase() + part.slice(1);
});
}
// or
function camelize(string) {
var parts = string.split('-'),
result = ""
for (var i = 1; i < parts.length; i++) {
result += parts[i].charAt(0).toUpperCase() + parts[i].slice(1)
}
return result;
}
First of all, you should concatenate results in some variable, instead of returning in loop.
Secondly fo not forget to add first element of array, since your loop is starting from 1.
function camelize(strg) {
var char = strg.split('-'), result = char[0]
for (var i = 1; i < char.length; i++) {
result += char[i].charAt(0).toUpperCase() + char[i].slice(1)
}
return result
}
alert(camelize("background-color"));
alert(camelize("list-style-image"));
Here is fiddle:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.