2016-01-18 94 views
-2

獲取一些代碼以便將字符串中每個單詞的首字母大寫。有人可以幫助我更新它,這樣它也可以刪除字符串中的所有空格,一旦第一個字母被封閉。首字母大寫並刪除字符串中的空格

return function (str) { 
    return str.replace(/\w\S*/g, function(txt) { 
     return txt.charAt(0).toUpperCase() + txt.substr(1); 
    }); 
} 
+0

[This](http://codereview.stackexchange.com/questions/77614/capitalize-the-first-character-of-all-words-even-when-following-a)解釋瞭如何將每個首字母大寫。 –

+1

可能重複[在JavaScript中首字母大寫](http://stackoverflow.com/questions/1026069/capitalize-the-first-letter-of-string-in-javascript) –

回答

0

試試這個:

var input = 'lorem ipsum dolor sit amet'; 
 

 
var output = input.replace(/\w+/g, function(txt) { 
 
    return txt.charAt(0).toUpperCase() + txt.substr(1); 
 
}).replace(/\s/g, ''); 
 

 
document.getElementById('output').innerHTML = output;
<div id="output"></div>

+1

工作過很多感謝。決定接受這個答案,因爲它對於尋找這個答案的其他開發者來說更​​加徹底和理想:) – Richy

+0

@Richy好吧。請享用。但是,我之前首先給出了完全相同的答案,所以如果你認爲公平,只有我沒有做的事情是提供一個片段。對?我會確保我從下一步開始。 –

0

您可以像使用一個簡單的輔助功能:

return function (str) { 
    return str.replace(/\w\S*/g, function(txt) { 
     return txt.charAt(0).toUpperCase() + txt.substr(1); 
    }).replace(/\s/g, ""); 
} 
+0

這將只適用於第一個字。 – jcubic

+0

工作過。非常感謝:) – Richy