如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
这里是我的尝试,使一个普遍的功能,只有第一字母,或每个字母的第一字母,包括单词分开的单词(如一些第一名在法语)。
默认情况下,该函数仅将第一个字母归功,其余的字母无触。
参数:
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 );
}
}
}
其他回答
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
一些其他答案修改 String.prototype(这个答案也被用来),但我会建议反对这一点现在由于可持续性(很难找到函数在哪里被添加到原型,如果另一个代码使用相同的名称 / 一个浏览器添加一个原始函数与相同的名称在未来可能导致冲突)。
我只会用一个常见的表达式:
myString = ' the quick green alligator...';
myString.trim().replace(/^\w/, (c) => c.toUpperCase());
var a = "this is a test"
console.log(a.replace(/^[a-z]/g, txt => txt.toUpperCase()));
已经有这么多好答案,但你也可以使用一个简单的CSS转换:
text-transform: capitalize;
div.text-capitalize { 文本转型:资本化; } <h2>文本转型:资本化:</h2> <div class="text-capitalize">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>
let capitalize = (strPara)=>{
let arr = Array.from(strPara);
arr[0] = arr[0].toUpperCase();
return arr.join("");
}
let str = capitalize("this is a test");
console.log(str);