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

例如:

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


当前回答

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)

其他回答

var nameP = prompt("please enter your name");
var nameQ = nameP.slice(0,1);
var nameR = nameP.slice(1,100);
nameQ = nameQ.toUpperCase();
nameP = nameQ + nameR;
console.log("Hello! " + nameP);

出口:

Hello! Alex

或者你可以使用Sugar.js资本()

例子:

'hello'.capitalize()           -> 'Hello'
'hello kitty'.capitalize()     -> 'Hello kitty'
'hello kitty'.capitalize(true) -> 'Hello Kitty'
String.prototype.capitalize = function(){
    return this.replace(/(^|\s)([a-z])/g, 
                        function(m, p1, p2) {
                            return p1 + p2.toUpperCase();
                        });
};

使用:

capitalizedString = someString.capitalize();

此分類上一篇: This Is a Text String

这将容忍可能领先的白空间,并不会错过一条线中的第一字母的目标,因此,它可能会改善已经在线上可用的好解决方案。

str = "   the Eifel Tower";
str.replace(/\w/, str.match(/\w/)[0].toUpperCase());
>> "   The Eifel Tower";

但是,如果对白条行进行执行,则会导致“软”错误,为了避免这种可能的错误或对白条行或数字进行不必要的处理,可以使用温和的条件警卫:

+str!=+str ?  str.replace(/\w/, str.match(/\w/)[0].toUpperCase()) : str;

ucfirst函数工作,如果你这样做。

function ucfirst(str) {
    var firstLetter = str.slice(0,1);
    return firstLetter.toUpperCase() + str.substring(1);
}

谢谢JP的解释。