2016-01-18 96 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