Javascript 如何将每个单词的第一个字母大写,例如 2 个单词的城市?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4878756/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to capitalize first letter of each word, like a 2-word city?
提问by pepe
My JS woks well when the city has one word:
当城市只有一个词时,我的 JS 工作得很好:
- cHIcaGO ==> Chicago
- 芝加哥 ==> 芝加哥
But when it's
但是当它
- 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();
}
回答by Dexter
There's a good answer here:
有一个很好的答案在这里:
function toTitleCase(str) {
return str.replace(/\w\S*/g, function(txt){
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
}
or in ES6:
或在 ES6 中:
var text = "foo bar loo zoo moo";
text = text.toLowerCase()
.split(' ')
.map((s) => s.charAt(0).toUpperCase() + s.substring(1))
.join(' ');
回答by capdragon
You can use CSS:
您可以使用 CSS:
p.capitalize {text-transform:capitalize;}
Update (JS Solution):
更新(JS解决方案):
Based on Kamal Reddy's comment:
基于 Kamal Reddy 的评论:
document.getElementById("myP").style.textTransform = "capitalize";
回答by maerics
function convertCase(str) {
var lower = String(str).toLowerCase();
return lower.replace(/(^| )(\w)/g, function(x) {
return x.toUpperCase();
});
}
回答by u476945
The JavaScript function:
JavaScript 函数:
String.prototype.capitalize = function(){
return this.replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase(); } );
};
To use this function:
要使用此功能:
capitalizedString = someString.toLowerCase().capitalize();
Also, this would work on multiple words string.
此外,这适用于多个单词字符串。
To make sure the converted City name is injected into the database, lowercased and first letter capitalized, then you would need to use JavaScript before you send it over to server side. CSS simply styles, but the actual data would remain pre-styled. Take a look at this jsfiddleexample and compare the alert message vs the styled output.
为了确保将转换后的城市名称注入数据库,小写首字母大写,然后您需要在将其发送到服务器端之前使用 JavaScript。CSS 只是简单的样式,但实际数据将保持预样式。看看这个jsfiddle示例并比较警报消息与样式输出。