How to capitalize first letter of each word, like a 2-word city? [duplicate]

How to capitalize first letter of each word, like a 2-word city? [duplicate]

This question already has an answer here:

Convert string to title case with JavaScript

50 answers

My JS woks well when the city has one word:

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();
}

Solutions/Answers:

Solution 1:

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(' ');

Solution 2:

You can use CSS:

p.capitalize {text-transform:capitalize;}

Solution 3:

function convertCase(str) {
  var lower = String(str).toLowerCase();
  return lower.replace(/(^| )(\w)/g, function(x) {
    return x.toUpperCase();
  });
}

Solution 4:

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.

Related:  How to compile a project properly with Babel and Grunt