问题
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