James Barr James Barr - 7 months ago 14
Javascript Question

Javascript string conversion to 'Title Case' returns no output

I can't pinpoint where the error in the code is, it produces no output:

function capitalize (x) {
var arr = x.split(' ');
var output = [];

for (var i = 0; i < arr.length; i++) {

output.push(arr[x].charAt(0).toUpperCase()+arr[x].slice(1));
};

return output.join(' ');
}

alert(capitalize("the quick brown fox"));

Answer

I believe arr[x] should be arr[i].

function capitalize (x) {
        var arr = x.split(' ');
        var output = [];

        for (var i = 0; i < arr.length; i++) {

            output.push(arr[i].charAt(0).toUpperCase()+arr[i].slice(1));
        };

        return output.join(' ');
    }

    alert(capitalize("the quick brown fox"));

Comments