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

例如:

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


当前回答

您可以使用 String#chatAt 获取第一个字符,将其转向上方,然后将其与链条的剩余部分相结合。

function capitalizeFirstLetter(v) {
  return v.charAt(0).toUpperCase() + v.substring(1);
}

其他回答

目前投票的答案是正确的,但它不会在资本化第一个字符之前切断或检查链条的长度。

String.prototype.ucfirst = function(notrim) {
    s = notrim ? this : this.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g,'').replace(/\s+/g,' ');
    return s.length > 0 ? s.charAt(0).toUpperCase() + s.slice(1) : s;
}

设置 notrim 论点,以防止第一条线被推翻:

'pizza'.ucfirst()         => 'Pizza'
'   pizza'.ucfirst()      => 'Pizza'
'   pizza'.ucfirst(true)  => '   pizza'

使用 RamdaJs 的另一种方式,是功能编程方式:

firstCapital(str){
    const fn = p => R.toUpper(R.head(p)) + R.tail(p);
    return fn(str);
}

用多个字在一个字符串:

firstCapitalAllWords(str){
    const fn = p => R.toUpper(R.head(p)) + R.tail(p);
    return R.map(fn,R.split(' ', str)).join(' ');
}
String.prototype.capitalize = function(allWords) {
   return (allWords) ? // If all words
      this.split(' ').map(word => word.capitalize()).join(' ') : // Break down the phrase to words and then recursive
                                                                 // calls until capitalizing all words
      this.charAt(0).toUpperCase() + this.slice(1); // If allWords is undefined, capitalize only the first word,
                                                    // meaning the first character of the whole string
}

然后:

 "capitalize just the first word".capitalize(); ==> "Capitalize just the first word"
 "capitalize all words".capitalize(true); ==> "Capitalize All Words"

更新2016年11月(ES6),只是为了乐趣:

const capitalize = (string = '') => [...string].map(    // Convert to array with each item is a char of
                                                        // string by using spread operator (...)
    (char, index) => index ? char : char.toUpperCase()  // Index true means not equal 0, so (!index) is
                                                        // the first character which is capitalized by
                                                        // the `toUpperCase()` method
 ).join('')                                             // Return back to string

此分類上一篇: 你好(Hello)

安装和加载Lodash:

import { capitalize } from "lodash";

capitalize('test') // Test

一条线(“输入线可以设置到任何条线”):

inputString.replace(/.{1}/, inputString.charAt(0).toUpperCase())