如何在 JavaScript 中使字符串的第一个字母大写?
技术问答
545 人阅读
|
0 人回复
|
2023-09-11
|
如何在不改变任何其他字母的情况下大写字符串的第一个字母?' |/ \9 c! j. _" Q4 R2 O- F
例如:: R0 o( [" t) j# F' k) _
"this is a test" → "This is a test"
( F+ o5 S) x) T; V3 @"the Eiffel Tower" → "The Eiffel Tower"
% Z# i% _! B" l2 T6 O+ J' v1 h"/index.html" → "/index.html"
4 W% j( r1 Y; l, h) b5 B! X0 M) e 解决方案: # ^0 N8 R8 O" I, {8 s3 T" u U
基本的解决方案是:; s' ` [1 j2 X& E* `
function capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() string.slice(1);}console.log(capitalizeFirstLetter('foo); // Foo
% ?; ^' D% A! k7 g$ i* t' T( c 修改了其他答案String.prototype(这个答案也曾经修改过),但由于可维护性,我现在建议不要这样做(很难找出函数被添加到的位置prototype,如果其他代码使用相同的名称/浏览器,将来可能会导致冲突添加相同名称的本机函数)。5 R8 q+ P$ g" {- M+ P
若要使用 Unicode 代码点而不是代码单元(如处理基本多语言平面以外的 Unicode 字符),你可以用String#[@iterator]使用代码点的事实,你可以使用它toLocaleUpperCase获取区域设置正确的大写:
9 [5 z! I, F; w6 C2 Z1 Aconst capitalizeFirstLetter = ([ first,...rest ],locale = navigator.language) => first.toLocaleUpperCase(locale) rest.join('')console.log( capitalizeFirstLetter('foo// Foo capitalizeFirstLetter("????????????"),// "????????????" (correct!) capitalizeFirstLetter("italya",'tr // talya" (correct in Turkish Latin!))' E* h! \0 a, r( P/ C/ k- w
|
|
|
|
|
|