简体   繁体   中英

Capitalizing first letter of each word malfunction when word contains special character

I am using this line to capitalize all the first alphabets of each word

text.replace(/\b\w^\w/g, l => l.toUpperCase());

it successfully capitalize normal words eg asif saeed -> Asif Saeed

but when capitalizing name like "anna alàs i jové" it converts this to "Anna AlàS I Jové" S should not be capital after à . Plus can we have a solution in which it ignore the word with single alphabet.

The best and easiest way to capitalize the first alphabet is:

function toTitleCase(str)
{
    return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}
console.log(toTitleCase("anna alàs i jové"));

EDIT :

To include the words starting with German characters you can use:

function toTitleCase1(str)
   {
        return str.replace(/[\w\xc0-\xd6\xd8-\xf6\xf8-\xff]+/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
   }
console.log(toTitleCase1("ànna alàs i jové"));

Please try this.

 var text = "anna alàs i jové"; String.prototype.initCap = function() { return this.toLowerCase().replace(/(?:^|\\s)[az]/g, function(m) { return m.toUpperCase(); }); }; if (/^[a-zA-Z0-9- ]*$/.test(text) == false) { //Inint cap console.log(text.initCap()); //Init cap if length >1 var temp = text.split(" "); var t = ""; temp.map(function(value){ if(value.length > 1){ t += value.initCap() + " "; }else{ t += value + " "; } }); console.log(t); } 

this will solve Your problem. http://plnkr.co/edit/7ggKNRw7nwCLmPN0y4Az?p=preview

      return str.toLowerCase().replace(/\b(\w)/g, s => s.toUpperCase());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM