How to capitalize first letter of each word, like

2019-01-01 06:18发布

问题:

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:

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

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


回答2:

You can use CSS:

p.capitalize {text-transform:capitalize;}


回答3:

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


回答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.



标签: javascript