Javascript/jQuery uppercase first letter of variable with accents

拥有回忆 提交于 2019-12-11 04:35:56

问题


I have a form with some text inputs to insert First Name, Last Name of a person, but I want to change the first letter of each word to a Uppercase and I found this solution:

 // The textboxes with this class are modified
 $(".toUpper").change(function () {
        var str = $(this).val();
        str = str.toLowerCase().replace(/\b[a-z]/g, function (letter) {
            return letter.toUpperCase();

        });
        $(this).val(str);
    });

and it works, ("hEllO"=>"Hello", "whAts uP" =>"Whats Up").

The problem occurs when I try to apply this to an accented word, Example:

"gonzález" = "GonzáLez",
"pérez" = "PéRez"

After an accented word there is a Uppercase letter again.

How can I modify the regular expression to avoid this issue?

hope you can help me!! :)


回答1:


\b is a non word boundary (i.e \b would make a boundary for any any character which doesn't belong to any 1 of [0-9a-zA-Z_])

So those accented word become the boundary for your word..

Instead use this regex

/(^|\s)[a-z\u00E0-\u00FC]/g



回答2:


[a-z] doesn't match é. You'll have to be a bit more lenient:

"gonzález foo bar, baz él".replace(/(^|\s)\S/g, function(match) {
    return match.toUpperCase();
});

And the output:

"González Foo Bar, Baz Él"


来源:https://stackoverflow.com/questions/16573099/javascript-jquery-uppercase-first-letter-of-variable-with-accents

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!