如果是字母,我该如何创建一条字符的第一个字符,但不会改变其他字符中的任何一个字符的案例?

例如:

“这是一个测试” → “这是一个测试” “埃菲尔塔” → “埃菲尔塔” “/index.html” → “/index.html”


当前回答

或者你可以使用Sugar.js资本()

例子:

'hello'.capitalize()           -> 'Hello'
'hello kitty'.capitalize()     -> 'Hello kitty'
'hello kitty'.capitalize(true) -> 'Hello Kitty'

其他回答

使用 Tailwind CSS

<p class="capitalize">The quick brown fox</p>

此分類上一篇: Quick Brown Fox

(src: https://tailwindcss.com/docs/text-transform#transforming-text)

只是因为这是一个真正的单线,我会包括这个答案. 这是一个基于ES6的交叉线单线。

let setStringName = 'the Eiffel Tower';
setStringName = `${setStringName[0].toUpperCase()}${setStringName.substring(1)}`;

我尝试了不同的方法。

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 ) 和

function capitalize(s) {
    // returns the first letter capitalized + the string from index 1 and out aka. the rest of the string
    return s[0].toUpperCase() + s.substr(1);
}


// examples
capitalize('this is a test');
=> 'This is a test'

capitalize('the Eiffel Tower');
=> 'The Eiffel Tower'

capitalize('/index.html');
=> '/index.html'

下面是更清洁、更美丽的版本。

var str = '';
return str.replace(new RegExp('^'+str[0]+''), str[0].toUpperCase());

结果:

這是一個測試 -> 這是一個測試