2015-12-11 35 views
1

我已經查找了如何大寫字符串的每個單詞的第一個字符,但沒有任何幫助。我需要將輸入的字符串設置爲標題大寫字母小寫字母。 我已經試過這樣:如何在JavaScript中捕獲每個字符串的第一個字符?

function titleCase(str) { 
 
//converting the giving string into array 
 
    str =str.split(" "); 
 
//iterating over all elem.s in the array 
 
    for(var i=0;i<str.length;i++){   
 
//converting each elem. into string 
 
    str[i]=str[i].toString(); 
 
//converting the first char to upper case &concatenating to the rest chars 
 
    str[i]=str[i].toUpperCase(str[i].charAt(0))+ str[i].substring(1); 
 
    } 
 
    return str; 
 
} 
 
titleCase("I'm a little tea pot");

+0

你是指每個字符串的第一個字符? – gurvinder372

+2

請在這裏找到答案[在JavaScript中首字母大寫](http://stackoverflow.com/questions/1026069/capitalize-the-first-letter-of-string-in-javascript) –

+0

是'I'小茶壺'預計輸出 – Tushar

回答

1
function firstToUpperCase(str) { 
    return str.substr(0, 1).toUpperCase() + str.substr(1); 
} 

var str = 'hello, I\'m a string'; 
var uc_str = firstToUpperCase(str); 

console.log(uc_str); //Hello, I'm a string 
1

你可以簡單地做:

function capitalFirst(str) { 
    return str.charAt(0).toUpperCase() + str.slice(1); 
} 
1
function capitalise(string) { 
     return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase(); 
    } 
    capitalise("smallletters") ;// Smallletters 
1

,如果你想爲大寫的每個單詞的第一個字符字符串(看起來像你在做什麼你的代碼)

function titleCase(str) { 
    str =str.split(" "); 
    for(var i=0;i<str.length;i++) 
    {   
    str[i]=str[i].charAt(0).toUpperCase + str[i].substring(1); 
    } 
    return str.join(" "); 
} 
alert(titleCase("I'm a little tea pot")); 
+1

這是正確答案... – benzkji

1

嘗試這樣:

String.prototype.titleCase = function(){ 
    return this[0].toUpperCase() + this.slice(1) 
} 

用法:

"hello my name is Jacques".titleCase(); 

如果你想利用每個單詞開頭的字符,嘗試這樣的事情:

String.prototype.capitalize = function(){ 
    return this.split(" ") 
       .map(function(){ 
        return this[0].toUpperCase() + this.slice(1); 
       }).join(" "); 
} 
相關問題