Format lowercased string to capitalize the begining of each sentence

Viewed 5491

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?

4 Answers

This JS function will apply sentence case to the initial sentence and any sentences that follow a sentence that ends with . ? !

function applySentenceCase(str) {
    var txt = str.split(/(.+?[\.\?\!](\s|$))/g);
    for (i = 0; i < (txt.length-1); i++) {
        if (txt[i].length>1){
            txt[i]=txt[i].charAt(0).toUpperCase() + txt[i].substr(1).toLowerCase();
        } else if (txt[i].length==1) {
            txt[i]=txt[i].charAt(0).toUpperCase();
        }
    }
    txt = txt.join('').replace(/\s\s/g,' ');
    return txt;
}

alert(applySentenceCase("LOREM IPSUM DOLOR SIT AMET, CONSECTETUR ADIPISCING ELIT. sed congue hendrerit risus, ac viverra magna elementum in. InTeRdUm Et MaLeSuAdA fAmEs Ac AnTe IpSuM pRiMiS iN fAuCiBuS. phasellus EST purus, COMMODO vitae IMPERDIET eget, ORNARE quis ELIT."));

Related