如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
在 CoffeeScript 中,添加一个字符串的原型:
String::capitalize = ->
@substr(0, 1).toUpperCase() + @substr(1)
使用将是:
"woobie".capitalize()
谁得益:
"Woobie"
其他回答
这里是我的尝试,使一个普遍的功能,只有第一字母,或每个字母的第一字母,包括单词分开的单词(如一些第一名在法语)。
默认情况下,该函数仅将第一个字母归功,其余的字母无触。
参数:
lc: 忠于强迫下载的所有字(s): 忠于资本化每一个字
if( typeof String.prototype.capitalize !== "function" ) {
String.prototype.capitalize = function( lc, all ) {
if( all ) {
return this.split( " " )
.map( currentValue => currentValue.capitalize( lc ), this )
.join( " " )
.split( "-" )
.map( currentValue => currentValue.capitalize( false ), this )
.join( "-" );
} else {
return lc
? this.charAt( 0 ).toUpperCase() + this.slice( 1 ).toLowerCase()
: this.charAt( 0 ).toUpperCase() + this.slice( 1 );
}
}
}
对于另一个案例,我需要它来资本化第一封信,下载其余的案例,下列案例让我改变了这个功能:
//es5
function capitalize(string) {
return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
capitalize("alfredo") // => "Alfredo"
capitalize("Alejandro")// => "Alejandro
capitalize("ALBERTO") // => "Alberto"
capitalize("ArMaNdO") // => "Armando"
// es6 using destructuring
const capitalize = ([first,...rest]) => first.toUpperCase() + rest.join('').toLowerCase();
看看这个解决方案:
var stringVal = 'master';
stringVal.replace(/^./, stringVal[0].toUpperCase()); // Returns Master
我在我的开发环境中使用这些线路,特别是当我与HTTP等API合作时:
假设您有一个 HTTP 标题,您希望在其名义中资本化每个初始字母,并在其组成词之间添加混合物。
'access control allow origin'
.replace(/\b\w/g, function (match) {
return match.toUpperCase();
})
.split(' ')
.join('-');
// Output: 'Access-Control-Allow-Origin'
这可能不是最优雅和最有吸引力的功能定义,但它肯定会完成工作。
有一个非常简单的方式来实现它通过替代。
'foo'.replace(/^./, str => str.toUpperCase())
结果:
'Foo'