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

Javascript

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

You can use CSS:

p.capitalize {text-transform:capitalize;}
Update (JS Solution):

Based on Kamal Reddy's comment:

document.getElementById("myP").style.textTransform = "capitalize";

Solution 3 - Javascript

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

Solution 4 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpepeView Question on Stackoverflow
Solution 1 - JavascriptDexterView Answer on Stackoverflow
Solution 2 - JavascriptcapdragonView Answer on Stackoverflow
Solution 3 - JavascriptmaericsView Answer on Stackoverflow
Solution 4 - JavascriptKJYe.NameView Answer on Stackoverflow