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

例如:

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


当前回答

在CSS中:

p::first-letter {
    text-transform:capitalize;
}

其他回答

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

这是一个简单的

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

你应该这样做:

let text = "lower case";
text = text.charAt(0).toUpperCase() + text.substring(1, text.length);
function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}

一些其他答案修改 String.prototype(这个答案也被用来),但我会建议反对这一点现在由于可持续性(很难找到函数在哪里被添加到原型,如果另一个代码使用相同的名称 / 一个浏览器添加一个原始函数与相同的名称在未来可能导致冲突)。

const capitalizeName = function (name) { 
    const names = name.split(' '); 
    const namesUpper = [];
    for (const n of names) {  
        namesUpper.push(n.replace(n[0], n[0].toUpperCase()));
    } 
    console.log(namesUpper.join(' '));
 }; 
capitalizeName('the Eiffel Tower')