如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?
例如:
“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”
当前回答
最短的 3 个解决方案, 1 和 2 处理 s 行是 “”, null 和 undefined 的情况:
s&&s[0].toUpperCase()+s.slice(1) // 32 char
s&&s.replace(/./,s[0].toUpperCase()) // 36 char - using regexp
'foo'.replace(/./,x=>x.toUpperCase()) // 31 char - direct on string, ES6
s=‘foo bar’; console.log( s&&s[0].toUpperCase()+s.slice(1) ); console.log( s&s.replace(/./,s[0].toUpperCase()); console.log( 'foo bar'.replace(/./,x=>x.toUpperCase()) );
其他回答
我只会用一个常见的表达式:
myString = ' the quick green alligator...';
myString.trim().replace(/^\w/, (c) => c.toUpperCase());
s[0].toUpperCase``+s.substr`1`
let s = 'hello there' console.log( s[0].toUpperCase''+s.substr`1` )
我最近在一个项目中需要类似的功能,这就是我如何实施它:
函数 capitlizeFirst(str) { // checks for null, undefined and empty string if (!str) return; return str.match("^[a-z]")? str.charAt(0).toUpperCase() + str.substring(1) : str; } console.log(capitlizeFirst("")); console.log(capitlizeFirst(null)); console.log(capitlizeFirst(undefined)); console.log(capitlizeFirst("hello world")); console.log(capitlizeFirst("/index.html"));
我尝试了不同的方法。
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 ) 和
优雅
const capitalize = ([firstChar, ...rest]) => `${firstChar.toUpperCase()}${rest.join('')}`;