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

例如:

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


当前回答

这是一个简单的

const upper = lower.replace(/^\w/, c => c.toUpperCase());

其他回答

首先,我只是想清楚资本化在这个背景下意味着什么,“这条线是资本化”可靠的来源

你可以从例子中看到,只要这不是OP正在寻找的东西,它应该说的是“我如何制作一条线的第一字”(不资本化线)

function ucfirst (str) {
    return typeof str != "undefined" ? (str += '', str[0].toUpperCase() + str.substr(1)) : '';
}

解释

typeof str != "undefined" // Is str set
? // true
str += '' // Turns the string variable into a string
str[0].toUpperCase() // Get the first character and make it upper case
+ // Add
str.substr(1) // String starting from the index 1 (starts at 0)
: // false
''; // Returns an empty string

这将与任何论点或没有论点工作。

undefined         === ""
""                === ""
"my string"       === "My string"
null              === "Null"
undefined         === "";
false             === "False"
0                 === "0"
true              === "True"
[]                === ""
[true,0,"",false] === "True,0,,false"

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

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

s[0].toUpperCase``+s.substr`1`

let s = 'hello there' console.log( s[0].toUpperCase''+s.substr`1` )

安装和加载Lodash:

import { capitalize } from "lodash";

capitalize('test') // Test