This question already has an answer here:
-
Convert string to title case with JavaScript
47 answers
My JS woks well when the city has one word:
But when it\'s
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();
}
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:
var text = \"foo bar loo zoo moo\";
text = text.toLowerCase()
.split(\' \')
.map((s) => s.charAt(0).toUpperCase() + s.substring(1))
.join(\' \');
You can use CSS:
p.capitalize {text-transform:capitalize;}
function convertCase(str) {
var lower = String(str).toLowerCase();
return lower.replace(/(^| )(\\w)/g, function(x) {
return x.toUpperCase();
});
}
The JavaScript function:
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 jsfiddle example and compare the alert message vs the styled output.