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

例如:

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


当前回答

我們可以獲得第一個角色與我最喜歡的RegExp之一,看起來像一個可愛的微笑: /^./

String.prototype.capitalize = function () {
  return this.replace(/^./, function (match) {
    return match.toUpperCase();
  });
};

对于所有咖啡豆:

String::capitalize = ->
  @replace /^./, (match) ->
    match.toUpperCase()

...和所有认为有更好的方式做到这一点的男孩,没有扩展原生原型:

var capitalize = function (input) {
  return input.replace(/^./, function (match) {
    return match.toUpperCase();
  });
};

其他回答

最简单的解决方案是:

let yourSentence = 'it needs first letter upper case';

yourSentence.charAt(0).toUpperCase() + yourSentence.substr(1);

或:

yourSentence.charAt(0).toUpperCase() + yourSentence.slice(1);

或:

yourSentence.substr(0, 1).toUpperCase() + yourSentence.substr(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 ) 和

使用 Tailwind CSS

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

此分類上一篇: Quick Brown Fox

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

尝试下列功能:

function capitalize (string) {
  return [].map.call(string, (char, i) => i ? char : char.toUpperCase()).join('')
}

使用:

capitalize('hello, world!')

结果:

Hello, world!

你应该这样做:

let text = "lower case";
text = text.charAt(0).toUpperCase() + text.substring(1, text.length);