如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
简单的ES6合成与模板链
const capitalize = (str) => { return `${str[0].toUpperCase()}${str.slice(1)}` // return str[0].toUpperCase() + str.slice(1) // without template string } console.log(capitalize(“这是一个测试”)); console.log(capitalize(“埃菲尔塔”)); console.log(capitalize(“/index.html”)); /* “这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/inde”
其他回答
有几种方法可以做到这一点,请尝试下面的
var lower = 'the Eiffel Tower';
var upper = lower.charAt(0).toUpperCase() + lower.substr(1);
如果你很舒服的常规表达,你会这样做:
var upper = lower.replace(/^\w/, function (chr) {
return chr.toUpperCase();
});
你甚至可以通过使用更现代化的合成来迈出一步:
const upper = lower.replace(/^\w/, c => c.toUpperCase());
此外,这也将照顾如示例中提到的负面场景,如从特殊字符开始的单词,如!@#$%^&*()}{{[];':",<>/?。
首先,我只是想清楚资本化在这个背景下意味着什么,“这条线是资本化”可靠的来源
你可以从例子中看到,只要这不是OP正在寻找的东西,它应该说的是“我如何制作一条线的第一字”(不资本化线)
function ucfirst (str) {
return typeof str != "undefined" ? (str += '', str[0].toUpperCase() + str.substr(1)) : '';
}
解释
typeof str != "undefined" // Is str set
? // true
str += '' // Turns the string variable into a string
str[0].toUpperCase() // Get the first character and make it upper case
+ // Add
str.substr(1) // String starting from the index 1 (starts at 0)
: // false
''; // Returns an empty string
这将与任何论点或没有论点工作。
undefined === ""
"" === ""
"my string" === "My string"
null === "Null"
undefined === "";
false === "False"
0 === "0"
true === "True"
[] === ""
[true,0,"",false] === "True,0,,false"
函数 capitalizeEachWord(str) { return str.replace(/\w\S*/g,函数(txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); }); } document.write(capitalizeEachWord('foo BAR God bAD'));
这里是我的尝试,使一个普遍的功能,只有第一字母,或每个字母的第一字母,包括单词分开的单词(如一些第一名在法语)。
默认情况下,该函数仅将第一个字母归功,其余的字母无触。
参数:
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 );
}
}
}
发表一个编辑 @salim 的答案,包括本地字母转换。
var str = "test string";
str = str.substring(0,1).toLocaleUpperCase() + str.substring(1);