To capitalize the first letter of a random string, you should follow these steps:
要大写随机字符串的第一个字母,应遵循以下步骤:
- Get the first letter of the string; 获取字符串的第一个字母;
- Convert the first letter to uppercase; 将第一个字母转换为大写;
- Get the remainder of the string; 获取字符串的其余部分;
- Concatenate the first letter capitalized with the remainder of the string and return the result; 将首个大写字母与字符串的其余部分连接起来并返回结果;
1.获取字符串的第一个字母 (1. Get the First Letter of the String)
You should use the charAt() method, at index 0, to select the first character of the string.
您应该使用索引为0的charAt()方法来选择字符串的第一个字符。
var string = "freeCodecamp";
string.charAt(0); // Returns "f"
NOTE: charAt
is preferable than using [ ]
(bracket notation) as str.charAt(0)
returns an empty string (''
) for str = ''
instead of undefined
in case of ''[0]
.
注意: charAt
比使用[ ]
(方括号表示法 )更str.charAt(0)
因为str.charAt(0)
)为str = ''
返回空字符串( ''
),而不是在''[0]
情况下undefined
。
2.将首字母转换为大写 (2. Convert the First Letter to uppercase)
You may use toUpperCase() method and convert the calling string to upper case.
您可以使用toUpperCase()方法并将调用字符串转换为大写。
var string = "freeCodecamp";
string.charAt(0).toUpperCase(); // Returns "F"
3.获取字符串的余数 (3. Get the Remainder of the String)
You may use slice() method and get the remainder of the string (from the second character, index 1, to the end of the string).
您可以使用slice()方法获取字符串的其余部分(从第二个字符index 1到字符串的末尾)。
var string = "freeCodecamp";
string.slice(1); // Returns "reeCodecamp"
4.返回结果加上字符串的第一个字母和其余部分 (4. Return the result adding the first letter and the remainder of the string)
You should create a function that accepts a string as only argument and returns the concatenation of the first letter capitalized string.charAt(0).toUpperCase()
and the remainder of the string string.slice(1)
.
您应该创建一个仅接受字符串作为参数的函数,并返回首字母大写字符串string.charAt(0).toUpperCase()
与字符串string.slice(1)
其余部分的串联。
var string = "freeCodecamp";
function capitalizeFirstLetter(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
capitalizeFirstLetter(string); // Returns "FreeCodecamp"
Or you may add that function to the String.prototype
for using it directly on a string using the following code (so that the method is not enumerable but can be overwritten or deleted later):
或者,您可以使用以下代码将该函数添加到String.prototype
以便直接在字符串上使用它( 这样该方法不可枚举,但以后可以覆盖或删除 ):
var string = "freeCodecamp";
/* this is how methods are defined in prototype of any built-in Object */
Object.defineProperty(String.prototype, 'capitalizeFirstLetter', {
value: function () {
return this.charAt(0).toUpperCase() + this.slice(1);
},
writable: true, // so that one can overwrite it later
configurable: true // so that it can be deleted later
});
string.capitalizeFirstLetter(); // Returns "FreeCodecamp"
资源 (Source)
stackoverflow - Capitalize the first letter of string in JavaScript
stackoverflow-将JavaScript中字符串的首字母大写
翻译自: https://www.freecodecamp.org/news/how-to-capitalize-the-first-letter-of-a-string-in-javascript/