Jason
Jason

Reputation: 7682

Only allow first letter to be capitalized in string (regex)

function toTitleCase(str){
    var styleName = $("a.monogramClassSelected").attr("styleKey");
        if (styleName == 'script') {
        return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();}).replace(/\s/, '');
        } else {
        return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
        }

}

This works (thanks to help below) - to remove spaces and have the first letter capitalized.

However, I need different functionality and did not frame my question correctly the first time.

I need to use regex to only allow the first letter to be capitalized. The string replace method above does not work fully, as a user can get around the method by using a space. So they could have "To Two". I need to rework the regex to only allow the first letter to be capitalized, regardless of spaces. (and the first letter does not have to be capitalized)

thanks for everyone's help so far!

Upvotes: 0

Views: 2282

Answers (3)

ajax333221
ajax333221

Reputation: 11754

This will do it:

function UppercaseFirst(str) {
    str = str.replace(/^\s+/, '');
    str = str.charAt(0).toUpperCase() + str.substr(1);
    return str
}

var mystring = " this is a test";

alert(UppercaseFirst(mystring));

Upvotes: 0

Devendra D. Chavan
Devendra D. Chavan

Reputation: 8991

This regular expression replaces all sequences of the form zero or exactly one space followed by capital letter by only the letter while keeping the rest of the text untouched (with multiple spaces allowed)

str.replace(/\s{0,1}([A-Z])(\s*\w*)/g, '$1$2');

The groups can be accessed by $1 and $2 in the replacement string.

regex explaination

Sample

Input " A person Who never made a mistake never tried anything new. - Albert Einstein :)"

Replaced string "A personWho never made a mistake never tried anything new. -AlbertEinstein :)"

In case you want to remove mutiple spaces instead of zero or one space preceding a capital letter then use \s* instead of \s{0,1} in the above expression.

Upvotes: 1

Suraj Chandran
Suraj Chandran

Reputation: 24791

To just remove the spaces, this works for me:

function toTitleCase(str){
    str = str.replace(/\s[A-Z]/, '');
    // str = str.replace(/[A-Z]\s/, '');
    return str;
}

Upvotes: 0

Related Questions