marcint339 marcint339 - 4 days ago 5
Javascript Question

Capitalize the beginning of each sentence

I would like to capitalize the beginning of each sentence. I have the following code from other question:

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


But if i don't put a dot for a last sentence, it doesn't work properly.
For example: for string "THIS IS THE FIRST QUESTION. SECOND QUESTION" it returns "This is the first question. SECOND QUESTION"

Answer

The issue with the regex is the grouping (...)

str.replace(/.+?(?:[.?!]\s|$)/g, function (txt) {
        return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    });
// Outputs
//"This is the first question. Second question. Third question

Changes

  • [.?!] This is a character class. There is no need to escape characters in a class.

  • (?:[.?!]\s|$) This matches . or ? or ! followed by a space(\s) OR an end of string $


What is wrong with .+?[\.\?\!](\s|$)

  • [\.\?\!](\s|$) This one tries to match a . or ? or ! always which is followed by a space or end of sentence. But clearly the last part didn't have one
Comments