Search code examples
javascriptregexstringlowercasecapitalization

Format lowercased string to capitalize the begining of each sentence


I have a string like

FIRST SENTENCE. SECOND SENTENCE.

I want to lowercase the string in that way to capitalize the first letter of each sentence.

For example:

string = string.toLowerCase().capitalize();

only the first sentence is capitalized.

I have the

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

function

Does anyone know how to solve?


Solution

  • If you only want to capitalize the first word of each sentence (not every word), then use this function:

    function applySentenceCase(str) {
        return str.replace(/.+?[\.\?\!](\s|$)/g, function (txt) {
            return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
        });
    }
    

    JSFiddle here

    If you want to keep the formatting of the rest of the sentence and just capitalize the first letters, change txt.substr(1).toLowerCase() to txt.substr(1)