如何将每个单词的首字母大写,如双字城市? [英] How to capitalize first letter of each word, like a 2-word city?
本文介绍了如何将每个单词的首字母大写,如双字城市?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当这个城市有一个词时,我的JS很好:
My JS woks well when the city has one word:
- cHIcaGO ==>芝加哥
但是当它是
- san diego ==> San diego
如何让它成为圣地亚哥?
How do I make it become San Diego?
function convert_case() {
document.profile_form.city.value =
document.profile_form.city.value.substr(0,1).toUpperCase() +
document.profile_form.city.value.substr(1).toLowerCase();
}
推荐答案
有一个很好的答案这里:
function toTitleCase(str) {
return str.replace(/\w\S*/g, function(txt){
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
}
或在ES6中:
var text = "foo bar loo zoo moo";
text = text.toLowerCase()
.split(' ')
.map((s) => s.charAt(0).toUpperCase() + s.substring(1))
.join(' ');
这篇关于如何将每个单词的首字母大写,如双字城市?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文