如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
我一直在试图做同样的事情(即;资本化第一字母在一个字符串,而它是打字)使用jQuery. 我搜索所有通过网页的答案,但我找不到它. 但是我能够得到一个工作周围使用on()函数在jQuery如下:
$("#FirstNameField").on("keydown",function(e){
var str = $("#FirstNameField").val();
if(str.substring()===str.substring(0,1)){
$("#FirstNameField").val(str.substring(0,1).toUpperCase());
}
});
这个功能实际上资本化了第一个字母,而数据输入者则不断打字。
其他回答
最简单的解决方案是:
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);
String.prototype.capitalize = function(allWords) {
return (allWords) ? // If all words
this.split(' ').map(word => word.capitalize()).join(' ') : // Break down the phrase to words and then recursive
// calls until capitalizing all words
this.charAt(0).toUpperCase() + this.slice(1); // If allWords is undefined, capitalize only the first word,
// meaning the first character of the whole string
}
然后:
"capitalize just the first word".capitalize(); ==> "Capitalize just the first word"
"capitalize all words".capitalize(true); ==> "Capitalize All Words"
更新2016年11月(ES6),只是为了乐趣:
const capitalize = (string = '') => [...string].map( // Convert to array with each item is a char of
// string by using spread operator (...)
(char, index) => index ? char : char.toUpperCase() // Index true means not equal 0, so (!index) is
// the first character which is capitalized by
// the `toUpperCase()` method
).join('') // Return back to string
此分類上一篇: 你好(Hello)
var capitalized = yourstring[0].toUpperCase() + yourstring.substr(1);
如果你去其中一个 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() 方法。
如果我可以稍微改变代码,我发现,如果我通过这个功能运行一条所有条线,什么都不会发生,所以......这里是我的条线。
String.prototype.capitalize = function(){
return this.toLowerCase().replace( /(^|\s)([a-z])/g , function(m, p1, p2) {
return p1 + p2.toUpperCase();
});
}