回答

收藏

如何在 JavaScript 中使字符串的第一个字母大写?

技术问答 技术问答 500 人阅读 | 0 人回复 | 2023-09-11

如何在不改变任何其他字母的情况下大写字符串的第一个字母?9 d, ~6 d2 S% n- t; v
例如:
7 b8 I+ v& q3 I"this is a test" → "This is a test"
4 y; ^1 s0 Y2 X9 C& F, i( T"the Eiffel Tower" → "The Eiffel Tower"0 x- x0 M* q2 `- A% E
"/index.html" → "/index.html"
                                                                3 i* ?' T0 m5 b4 T
    解决方案:                                                                " t, z! @$ H, I8 v! C
                                                                基本的解决方案是:3 M9 n! o  [# `  l4 V
    function capitalizeFirstLetter(string) {  return string.charAt(0).toUpperCase()   string.slice(1);}console.log(capitalizeFirstLetter('foo); // Foo/ S& V- a* r  T, X
修改了其他答案String.prototype(这个答案也曾经修改过),但由于可维护性,我现在建议不要这样做(很难找出函数被添加到的位置prototype,如果其他代码使用相同的名称/浏览器,将来可能会导致冲突添加相同名称的本机函数)。0 Y5 }+ t& \" z; T2 d  K
若要使用 Unicode 代码点而不是代码单元(如处理基本多语言平面以外的 Unicode 字符),你可以用String#[@iterator]使用代码点的事实,你可以使用它toLocaleUpperCase获取区域设置正确的大写:9 Q" d% O( o7 b) o* R0 g* X
    const 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!))) ~8 a& L& v3 @# _. |; L% a
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则