如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
String.prototype.capitalize = function(){
return this.replace(/(^|\s)([a-z])/g,
function(m, p1, p2) {
return p1 + p2.toUpperCase();
});
};
使用:
capitalizedString = someString.capitalize();
此分類上一篇: This Is a Text String
其他回答
下面有一个函数称为ucfirst((缩写为“上例第一字母”):
function ucfirst(str) {
var firstLetter = str.substr(0, 1);
return firstLetter.toUpperCase() + str.substr(1);
}
您可以通过称 ucfirst(“某些链条”)来资本化一个链条 - 例如,
ucfirst("this is a test") --> "This is a test"
在第一行中,它提取第一Letter,然后在第二行中,它通过呼叫第一Letter.toUpperCase()来资本化第一Letter,并将其与其余的行列相结合,这是通过呼叫str.substr(1)来找到的。
你可能认为这会失败一个空的线条,而且实际上在一个语言如C,你会不得不为此加密,但是在JavaScript中,当你采取一个空的线条,你只是得到一个空的线条。
每个链条的第一个字符都被资本化了。
函数资本化(词){返回词[0].toUpperCase() + word.slice(1).toLowerCase(); } console.log(capitalize(“john”)); //John console.log(capitalize(“BRAVO”)); //Bravo console.log(capitalize(“BLAne”)); //Blane
如果你想在一行中资本化每个第一封信,例如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");
这个解决方案可能是新的,也许是最简单的。
函数第一UpperCase(输入) {返回输入[0].toUpperCase() + input.substr(1); } console.log(第一UpperCase(“资本化第一字母”));
如果我可以稍微改变代码,我发现,如果我通过这个功能运行一条所有条线,什么都不会发生,所以......这里是我的条线。
String.prototype.capitalize = function(){
return this.toLowerCase().replace( /(^|\s)([a-z])/g , function(m, p1, p2) {
return p1 + p2.toUpperCase();
});
}