AlvaroGlez AlvaroGlez - 1 year ago 84
Javascript Question

How i can Capitalize without using toUpperCase

How I can capitalize a word without using .toUpperCase() ... string.prototype.capitalize or Regex maybe ?

Only the first letter of the word.

I have this, and works perfectly:

text.charAt(0).toUpperCase() + text.slice(1);

But i don't want use .toUpperCase().

PD: only use JS, not CSS.


Answer Source

You can use fromCharCode and charCodeAt to switch between lower and upper letter:

function capitalize(word) {
    var firstChar = word.charCodeAt(0);
    if (firstChar >= 97 && firstChar <= 122) {
        return String.fromCharCode(firstChar - 32) + word.substr(1);
    return word;

    capitalize("abcd") + "\n" +
    capitalize("ABCD") + "\n" +
    capitalize("1bcd") + "\n" +

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download