Javascript: Capitalize First Word of String (EASY)



In Javascript, you can make the first word uppercase by using the technique below.

function capitalize(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
}

var str = "lorem ipsum dolor";
capitalize(str); // output: "Lorem ipsum dolor"

To explain what's going on, the function takes the first letter of given string and convert it to uppercase then append to the rest of the given string.

We can modify the String.prototype if you don't mind a little setback on the performance.

String.prototype.capitalize = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}

Now we can call the function in object oriented way:
var str = "lorem ipsum dolor";
console.log(str.capitalize()); // output: "Lorem ipsum dolor"

Comments