Amran Amran - 7 months ago 36
Javascript Question

Capitalize Words After Each dot (.) & Starting of a String

How to capitalize each words on starting of a string and after dot(.) sign?

I made a research on google and stackoverflow, below are the codes that I achieved but this will only capitalize starting of a string. Example as belows;

var str = 'this is a text. hello world!';
str = str.replace(/^(.)/g, str[0].toUpperCase());

I want the string to be
This is a text. Hello world!.

I have tried to use css,
text-transform: capitalize;
but this will result in each word to be capitalize.


I use a function like this, that takes an optional second parameter that will convert the entire string to lowercase initially. The reason is that sometimes you have a series of Title Case Items. That You Wish to turn into a series of Title case items. That you wish to have as sentence case.

function sentenceCase(input, lowercaseBefore) {
    input = ( input === undefined || input === null ) ? '' : input;
    if (lowercaseBefore) { input = input.toLowerCase(); }
    return input.toString().replace( /(^|\. *)([a-z])/g, function(match, separator, char) {
        return separator + char.toUpperCase();

You would implement it in your example like so:

var str = 'this is a text. hello world!';
str = sentenceCase(str);
document.write(str); // This is a text. Hello world!