7

I want to capitalize all words in an input (using keyup function) to format names entered.

examples :

john doe => John Doe

JOHN DOE => John Doe

tommy-lee => Tommy-Lee

Currently, I use this code :

$("input").keyup(function() {
    var cp_value= ucwords($(this).val(),true) ;
    $(this).val(cp_value );
});

function ucwords(str,force){
    str=force ? str.toLowerCase() : str;  
    return str.replace(/(\b)([a-zA-Z])/g,
    function(firstLetter){
        return firstLetter.toUpperCase();
    });
}

But if the word contains an accentuated character, the following letter is also uppercased : John Döe => John DöE.

What is the best solution to get what I want ?

Thank you

Charles
  • 50,943
  • 13
  • 104
  • 142
user1010687
  • 73
  • 1
  • 4
  • 1
    It is not actually a jQuery problem as it is better solved using plain JS. See my answer below. – Lapple Oct 24 '11 at 12:38
  • `str.split(/(\s|-)+/).map(function( v ,i ){ return v.charAt(0).toUpperCase()+ v.slice(1).toLowerCase(); }).join('')` – rab Jun 18 '14 at 15:09

3 Answers3

9

Problem is with the word boundary if you do a manual boundary it works

function ucwords(str,force){
    str=force ? str.toLowerCase() : str;
    return str.replace(/(^([a-zA-Z\p{M}]))|([ -][a-zA-Z\p{M}])/g,
    function(firstLetter){
    return firstLetter.toUpperCase();
    });
}

and adding the Unicode for the accented characters as well

kamui
  • 3,339
  • 3
  • 26
  • 44
4

Use this one:

function ucwords(input) {
    var words = input.split(/(\s|-)+/),
        output = [];

    for (var i = 0, len = words.length; i < len; i += 1) {
        output.push(words[i][0].toUpperCase() +
                    words[i].toLowerCase().substr(1));
    }

    return output.join('');
}

Testing:

console.log(ucwords('JOHN   DOE'),
            ucwords('tommy-lee'),
            ucwords('TOMMY-lee'),
            ucwords('John Döe'));
Lapple
  • 3,385
  • 20
  • 20
0

you can do something like this after keyup split then get the fisrt char and uppercase it then join all. you can check this link i wrote a demo for you http://jsfiddle.net/vbx3x/5/

function ucwords(str,force){
 str=force ? str.toLowerCase() : str;  

 var temp= str.split(/(\s|-)+/);
for(var i=0; i<temp.length; i++) {
  temp[i] = temp[i].substr(0,1).toUpperCase() + temp[i].substr(1,temp[i].length-1)
}
 return temp.join(' ');  
}
erimerturk
  • 4,230
  • 25
  • 25
  • 1
    As per the OP's question, this will not capitalise the character after a hyphen – njr101 Oct 24 '11 at 12:29
  • Thanks for your response. It works fine for special chars, but not anymore for letters after the hyphen (cf.: http://jsfiddle.net/vbx3x/5/) – user1010687 Oct 24 '11 at 12:36
  • i updated the split part, i didnt see the other characters, "-|", etc. it is ok now, u can test it. – erimerturk Oct 24 '11 at 12:49