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

例如:

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


当前回答

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

其他回答

string = string.replace(string.charAt(0), string.charAt(0).toUpperCase());

好吧,所有答案都会崩溃,如果方法通过一些意想不到的数据类型,如对象或功能。

因此,要确保它不会在任何情况下崩溃,我们将需要检查类型。

首頁 〉外文書 〉文學 〉文學 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉 〉

我最近在一个项目中需要类似的功能,这就是我如何实施它:

函数 capitlizeFirst(str) { // checks for null, undefined and empty string if (!str) return; return str.match("^[a-z]")? str.charAt(0).toUpperCase() + str.substring(1) : str; } console.log(capitlizeFirst("")); console.log(capitlizeFirst(null)); console.log(capitlizeFirst(undefined)); console.log(capitlizeFirst("hello world")); console.log(capitlizeFirst("/index.html"));

当我们说资本时,这意味着每个字中的第一个字母应该在上方,而成功的字符则在下方。

第一個函數下有兩個函數,第一個函數將使一條字符的第一個字符在上方,成功的字符在下方,第二個函數將使一條字符在標題字符,這意味著每個字符的第一個字符將在頭部。

// Will make will first letter of a sentence or word uppercase function capital(word){ word = word.toLowerCase() return word[0].toUpperCase() + word.substring(1); } // Will make first letter in each word capital function titleCase(title) { title = title.toLowerCase(); const words = title.split(' '); const titleCaseWords = words.map(word) => word[0].toUpperCase() + word.substring(

我需要做一个完整的名字资本化,如阿米尔·迪亚菲(Amir Diafi),所以我分裂了链条,以获得这些名字的序列,并资本化了每个字母的第一字母。

const value = 'amir diafi karim mohammed' const splited_names = value.split(' ') let capitalizedValue = '' for (const iterator of splited_names) { capitalizedValue += ` ${iterator.charAt(0).toUpperCase()}${iterator.slice(1)}` } capitalizedValue.trim() console.log(capitalizedValue) //amir diafi karim => Amir Diafi Karim