如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
如果我可以稍微改变代码,我发现,如果我通过这个功能运行一条所有条线,什么都不会发生,所以......这里是我的条线。
String.prototype.capitalize = function(){
return this.toLowerCase().replace( /(^|\s)([a-z])/g , function(m, p1, p2) {
return p1 + p2.toUpperCase();
});
}
其他回答
你可以这样做,这样一行。
string[0].toUpperCase() + string.substring(1)
如果你想在一行中资本化每个第一封信,例如Hello to the world,你可以使用以下(由史蒂夫·哈里森重复):
function capitalizeEveryFirstLetter(string) {
var splitStr = string.split(' ')
var fullStr = '';
$.each(splitStr,function(index){
var currentSplit = splitStr[index].charAt(0).toUpperCase() + splitStr[index].slice(1);
fullStr += currentSplit + " "
});
return fullStr;
}
您可以通过使用以下方式呼叫:
capitalizeFirstLetter("hello to the world");
好吧,所以我是新的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);
出发:“我是聪明的......”;
这将容忍可能领先的白空间,并不会错过一条线中的第一字母的目标,因此,它可能会改善已经在线上可用的好解决方案。
str = " the Eifel Tower";
str.replace(/\w/, str.match(/\w/)[0].toUpperCase());
>> " The Eifel Tower";
但是,如果对白条行进行执行,则会导致“软”错误,为了避免这种可能的错误或对白条行或数字进行不必要的处理,可以使用温和的条件警卫:
+str!=+str ? str.replace(/\w/, str.match(/\w/)[0].toUpperCase()) : str;
目前投票的答案是正确的,但它不会在资本化第一个字符之前切断或检查链条的长度。
String.prototype.ucfirst = function(notrim) {
s = notrim ? this : this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,'').replace(/\s+/g,' ');
return s.length > 0 ? s.charAt(0).toUpperCase() + s.slice(1) : s;
}
设置 notrim 论点,以防止第一条线被推翻:
'pizza'.ucfirst() => 'Pizza'
' pizza'.ucfirst() => 'Pizza'
' pizza'.ucfirst(true) => ' pizza'