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

例如:

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


当前回答

您可以使用 regex 方法:

str.replace(/(^|\s)\S/g, letter => letter.toUpperCase());

其他回答

一个简单的,紧凑的功能,将完成你的工作:

const capitalize = str => str.split(' ').map(sub => sub.charAt(0).toUpperCase() + sub.slice(1)).join(' ');

“Foo” > “Foo” “Foo Bar” > “Foo Bar”

我們可以獲得第一個角色與我最喜歡的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();
  });
};
var str = "test string";
str = str.substring(0,1).toUpperCase() + str.substring(1);

对于另一个案例,我需要它来资本化第一封信,下载其余的案例,下列案例让我改变了这个功能:

//es5
function capitalize(string) {
    return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
capitalize("alfredo")  // => "Alfredo"
capitalize("Alejandro")// => "Alejandro
capitalize("ALBERTO")  // => "Alberto"
capitalize("ArMaNdO")  // => "Armando"

// es6 using destructuring 
const capitalize = ([first,...rest]) => first.toUpperCase() + rest.join('').toLowerCase();

使用原型

String.prototype.capitalize = function () {
    return this.charAt(0) + this.slice(1).toLowerCase();
  }

或使用功能

function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
}