如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
如果你去其中一个 regex 答案,请记住,它们只会与 ASCII 字符一起工作. 所有的 Unicode 字母都不会被打破. XRegExp 图书馆和其 Unicode 插件解决这个问题,如果你想与 regex 保持。
String.prototype.capitalize = function () {
return this.replace(XRegExp("^\\p{L}"), function ($0) { return $0.toUpperCase(); })
}
考虑到它仍然不涵盖所有可能性(混合字符,见 http://www.regular-expressions.info/unicode.html),似乎更容易使用.charAt(0).toUpperCase() 方法。
其他回答
好吧,所以我是新的JavaScript. 我无法得到上面的为我工作. 所以我开始把它自己。
String name = request.getParameter("name");
name = name.toUpperCase().charAt(0) + name.substring(1);
out.println(name);
在这里,我从一个表格中获取变量(它也手动工作):
String name = "i am a Smartypants...";
name = name.toUpperCase().charAt(0) + name.substring(1);
out.println(name);
出发:“我是聪明的......”;
第一封信与验证的资本化
function capitalizeFirstLetter(str) {
return (str && typeof str === 'string') ? (str.charAt(0).toUpperCase() + str.slice(1)) : "";
}
测试
console.log(capitalizeFirstLetter(0)); // Output: ""
console.log(capitalizeFirstLetter(null)); // Output: ""
console.log(capitalizeFirstLetter("test")); // Output: "Test"
console.log(capitalizeFirstLetter({})); // Output: ""
该方法将采取一个值,然后将其分成一系列的线条。
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
);
};
将所有单词的第一字母分为一个字符串:
function capitalize(str) {
return str.split(' ').map(word => word.charAt(0).toUpperCase() + word.toLowerCase().slice(1)).join(' ');
}
最简单的解决方案是:
let yourSentence = 'it needs first letter upper case';
yourSentence.charAt(0).toUpperCase() + yourSentence.substr(1);
或:
yourSentence.charAt(0).toUpperCase() + yourSentence.slice(1);
或:
yourSentence.substr(0, 1).toUpperCase() + yourSentence.substr(1);