如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
该方法将采取一个值,然后将其分成一系列的线条。
const firstLetterToUpperCase = value => {
return value.replace(
value.split("")["0"], // Split stirng and get the first letter
value
.split("")
["0"].toString()
.toUpperCase() // Split string and get the first letter to replace it with an uppercase value
);
};
其他回答
使用原型
String.prototype.capitalize = function () {
return this.charAt(0) + this.slice(1).toLowerCase();
}
或使用功能
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
}
好吧,所有答案都会崩溃,如果方法通过一些意想不到的数据类型,如对象或功能。
因此,要确保它不会在任何情况下崩溃,我们将需要检查类型。
首頁 〉外文書 〉文學 〉文學 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉
只是因为你可以,这并不意味着你应该,但是. 它需要 ECMAScript 6 因为代码使用序列破坏。
const capitalizeFirstLetter = s => {
const type = typeof s;
if (type !== "string") {
throw new Error(`Expected string, instead received ${type}`);
}
const [firstChar, ...remainingChars] = s;
return [firstChar.toUpperCase(), ...remainingChars].join("");
};
这里是我的版本,我认为它很容易理解和优雅。
var str = "foo bar baz";
// Capitalize
str.split(' ')
.map(w => w[0].toUpperCase() + w.substr(1).toLowerCase())
.join(' ')
// Returns "Foo Bar Baz"
// Capitalize the first letter
str.charAt(0).toUpperCase() + str.slice(1)
// Returns "Foo bar baz"
一条线路:
此分類上一篇: 重定向,重定向,重定向,重定向,重定向