如何在 JavaScript 中使字符串的第一个字母大写?
技术问答
544 人阅读
|
0 人回复
|
2023-09-11
|
如何在不改变任何其他字母的情况下大写字符串的第一个字母?
# X, P8 a. {: d2 j! Q' C8 f3 K例如:, }! y* N* b+ _. w' E P
"this is a test" → "This is a test"2 X+ D, J0 D5 b% _4 I# K
"the Eiffel Tower" → "The Eiffel Tower"
9 ?2 A1 Y9 t. ?; H' @/ N"/index.html" → "/index.html" / U7 W) J. N" G+ s2 n! ~7 T/ z
解决方案: , r, }6 I k1 M0 }" q' |1 R& _
基本的解决方案是:
4 W- [( x$ Z e: G8 K. u4 P$ Mfunction capitalizeFirstLetter(string) { return string.charAt(0).toUpperCase() string.slice(1);}console.log(capitalizeFirstLetter('foo); // Foo
8 H+ f! ?4 k# q( g- [/ c0 Z; { 修改了其他答案String.prototype(这个答案也曾经修改过),但由于可维护性,我现在建议不要这样做(很难找出函数被添加到的位置prototype,如果其他代码使用相同的名称/浏览器,将来可能会导致冲突添加相同名称的本机函数)。
3 z' f1 _' } J若要使用 Unicode 代码点而不是代码单元(如处理基本多语言平面以外的 Unicode 字符),你可以用String#[@iterator]使用代码点的事实,你可以使用它toLocaleUpperCase获取区域设置正确的大写:
4 v/ e5 o- ^0 E* Iconst 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!)), _ y% L% `/ Y
|
|
|
|
|
|