Reputation: 213
I got it working, all variations are displayed Sint-Anna
as should be, but I wonder, is there a more simple 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
.
Upvotes: 0
Views: 44
Reputation: 59252
String.prototype.capitalize = function(){
this.split('-').map(function(str){
return str[0].toUpperCase() + str.substr(1).toLowerCase();
}).join("-")
};
The above would be more succinct I suppose. It splits on -
and then maps, which captializes first letter and lower cases the others and then joins with -
using Array.join
Upvotes: 2