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

例如:

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


当前回答

function capitalize(string) {
    return string.replace(/^./, Function.call.bind("".toUpperCase));
}

其他回答

我們可以獲得第一個角色與我最喜歡的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();
  });
};

如果你想在一个字符串中资本化每一个字,你可以使用以下字符串:

'all_lowercase Capitalized lower_then_Upper a'.replace(/(?<=\b)[a-z](?=\w*)/g, c => c.toUpperCase())
// prints "All_lowercase Capitalized Lower_then_Upper A"

我们将使用CSS来实现这一点,它也可以从外部CSS设置。

<span text-transform="capitalize ">The first letter of each word becomes an upper case</span>

使用Vanilla JavaScript,我们可以:

let string = "test case"

string = string[0].toUpperCase() + string.substring(1)
//return "Test case"

此分類上一篇:</b/>

字符串[0].toUpperCase():将字符串中的第一个字符转换为顶部字符串

string.substring(1):在行中删除第一个字母并返回剩余的字符

text-transform="capitalize":在这个标签的顶部字母中创建每个字母的第一个字母. 如果您使用“uppercase”作为文本转换的值,标签中的每个字母将是一个字母。

带有箭功能

let fLCapital = s => s.replace(/./, c => c.toUpperCase())
fLCapital('this is a test') // "This is a test"

用火箭功能,另一种解决方案

let fLCapital = s => s = s.charAt(0).toUpperCase() + s.slice(1);
fLCapital('this is a test') // "This is a test"

与 Array 和 地图()

let namesCapital = names => names.map(name => name.replace(/./, c => c.toUpperCase()))
namesCapital(['james', 'robert', 'mary']) // ["James", "Robert", "Mary"]

将所有单词的第一字母分为一个字符串:

function capitalize(str) {
  return str.split(' ').map(word => word.charAt(0).toUpperCase() + word.toLowerCase().slice(1)).join(' ');
}