HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMajor

Capitalize the first character of all words (even when following a '-')

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
theallwordscharacterfollowingfirstcapitalizewheneven

Problem

I got it working, all variations are displayed Sint-Anna as should be, but I wonder, is there a simpler way to this, since it looks very cluttered?

String.prototype.capitalize = function(){
    var sa = this.replace(/-/g,' ');
    var saa = sa.toLowerCase();
    var sb = saa.replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase(); } );
    var sc = sb.replace(/\s+/g, '-');
    return sc;
};

console.log('sint-anna'.capitalize());
console.log('sint anna'.capitalize());
console.log('sint-Anna'.capitalize());
console.log('Sint Anna'.capitalize());
console.log('SiNt anna'.capitalize());
console.log('SINT ANNA'.capitalize());


Console:

Sint-Anna
Sint-Anna
Sint-Anna
Sint-Anna
Sint-Anna
Sint-Anna


There are no ways that there is a wrong input like Si ntAn na resulting in Si-Ntan-Na.

Solution

Your problem is an interesting one,but your solution is not a great use of regular expressions, since there's the better option of using the 'word boundary' anchor \b.

The boundary anchor matches a transition from a word, to a non-word, or vice versa. For this purpose, using the \w match to target word-characters after the \b is the right solution.

Note that the replace-function you give to the replace operation only needs the m argument now, there's no longer any sub-groups to process.

If your code was written as:

String.prototype.capitalize = function(){
        return this.toLowerCase().replace( /\b\w/g, function (m) {
            return m.toUpperCase();
        });
    };


then you would convert-to-lowercase, then locate the first letter of any word, and convert that to uppercase.

Putting that in to action, like:






type something in the box above



String.prototype.capitalize = function(){
return this.toLowerCase().replace( /\b\w/g, function (m) {
return m.toUpperCase();
});
};

var myInput = document.getElementById('myInput');
var myOutput = document.getElementById('myOutput')

myInput.addEventListener('input', function(e) {
myOutput.innerHTML = this.value.capitalize();
});


Code Snippets

String.prototype.capitalize = function(){
        return this.toLowerCase().replace( /\b\w/g, function (m) {
            return m.toUpperCase();
        });
    };

Context

StackExchange Code Review Q#77614, answer score: 25

Revisions (0)

No revisions yet.