如何使用Jquery连字符后将每个单词大写?

use*_*687 6 javascript jquery capitalize uppercase

我想大写输入中的所有单词(使用键盘功能)来格式化输入的名称.

例子 :

john doe => John Doe

JOHN DOE => John Doe

tommy-lee =>汤米 - 李

目前,我使用此代码:

$("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();
    });
}
Run Code Online (Sandbox Code Playgroud)

但是如果这个单词包含一个突出的字符,那么下面的字母也是大写的:JohnDöe=>JohnDöE.

得到我想要的最佳解决方案是什么?

谢谢

kam*_*mui 6

如果您使用手动边界,则问题在于边界

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();
    });
}
Run Code Online (Sandbox Code Playgroud)

并为重音字符添加Unicode