如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
string = string.replace(string.charAt(0), string.charAt(0).toUpperCase());
其他回答
下面是2018 ECMAScript 6+ 解决方案:
const str = 'The Eiffel Tower'; const newStr = `${str[0].toUpperCase()}${str.slice(1)}`; console.log('Original String:', str); // the Eiffel Tower console.log('New String:', newStr); // The Eiffel Tower
我尝试了不同的方法。
function myFun(val) {
var combain='';
for (let i = 0; i < val.length; i++) {
combain += val[i].charAt(0).toUpperCase() + val[i].substring(1, val[i].length)+'-';
}
return combain.replaceAll('-',' ');
}
var str = 'sreehari_bsn_alli'.replaceAll('_', ' ');
str = str.split(' ');
let op = myFun(str);
console.log(op ) 和
有一个非常简单的方式来实现它通过替代。
'foo'.replace(/^./, str => str.toUpperCase())
结果:
'Foo'
优雅
const capitalize = ([firstChar, ...rest]) => `${firstChar.toUpperCase()}${rest.join('')}`;
只是因为这是一个真正的单线,我会包括这个答案. 这是一个基于ES6的交叉线单线。
let setStringName = 'the Eiffel Tower';
setStringName = `${setStringName[0].toUpperCase()}${setStringName.substring(1)}`;