Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capitalize each word even after hyphens with Jquery?

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

like image 721
user1010687 Avatar asked Oct 24 '11 11:10

user1010687


2 Answers

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

like image 148
kamui Avatar answered Sep 25 '22 23:09

kamui


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'));
like image 37
Lapple Avatar answered Sep 24 '22 23:09

Lapple