284

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

4 Answers 4

704

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(' ');
14
  • 4
    just wondering (might be a newbie question) but how does javascript know that the txt in function(txt) parameter is referring to str? Is it because you are calling replace on str so it can assume that?
    – aug
    Aug 31, 2012 at 23:03
  • 5
    it's not actually passing in str - it's passing in the "matched substring" - e.g. the result of the regex. There's a good explanation on the Mozilla dev pages at developer.mozilla.org/en-US/docs/JavaScript/Reference/…, under the title Specifying a function as a parameter
    – Dexter
    Sep 1, 2012 at 11:46
  • 12
    Nice script but it doesn't work well for diacritics For example it will transform "anders ångström" into "Anders åNgström". If you need the script to handle such strings then check stackoverflow.com/questions/15150168/…
    – BearCode
    Aug 26, 2013 at 2:28
  • 6
    Might I recommend using \b\w instead of \w\S* as this will select the first letter of every word, even if the character inbetween is a slash or a dash rather than a space.
    – Barry
    Sep 15, 2015 at 20:10
  • 3
    DOESN'T work for non-english words.
    – Alexey Sh.
    Feb 26, 2016 at 10:17
150

You can use CSS:

p.capitalize {text-transform:capitalize;}

Update (JS Solution):

Based on Kamal Reddy's comment:

document.getElementById("myP").style.textTransform = "capitalize";
14
  • 2
  • 21
    you can't just use the text-transform: capitalize for cHIcaGO ==> Chicago. you would get CHIcaGO instead of Chicago. It simply transform only the first letter of the string.
    – KJYe.Name
    Feb 2, 2011 at 21:05
  • 13
    Downvoted because the question specifies JavaScript and you gave a solution using a different technology. Jan 6, 2017 at 6:46
  • 14
    I agree with @RichardSmith-Unna, the question specifies how to do this with Javascript. This answering is the equivalent of answering "How do I divide numbers with pencil and paper" with, "Get a calculator and use the division function".
    – Nick Res
    Feb 3, 2017 at 19:57
  • 5
    downvote due to not answering using the OPs requested language
    – dtburgess
    Feb 21, 2017 at 23:02
26
function convertCase(str) {
  var lower = String(str).toLowerCase();
  return lower.replace(/(^| )(\w)/g, function(x) {
    return x.toUpperCase();
  });
}
6
  • 1
    @enver's comment will not work since String.toUpperCase will be bound to the String object (this will be String, not the substring)
    – kikito
    Apr 1, 2013 at 12:17
  • 9
    ES6 shortcut: str.toLowerCase().replace(/(^| )(\w)/g, s => s.toUpperCase()) Feb 21, 2017 at 18:44
  • @ClaudioHolanda: ... which is the same as in the answer :) Mar 16, 2017 at 11:52
  • It don't work with accents, like "Úrsula" Sep 28, 2017 at 14:13
  • 1
    @rakensi I think you should erase your comment, I saw you already know it didn't work as expected so there is no point in leaving it there... (thanks for try anyway) Mar 26, 2019 at 13:11
13

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.

3
  • 3
    Seems fine, but do not add this to String.prototype. Oct 3, 2016 at 3:56
  • if(!String.prototype.toTitleCase) { String.prototype.toTitleCase = function(){ return this.toLowerCase().replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase(); } ); }; } if you want to add to String.prototype and add a toLowerCase() Mar 3, 2017 at 4:01
  • 1
    It don't work with accents, like "Úrsula" Sep 28, 2017 at 14:19

Not the answer you're looking for? Browse other questions tagged or ask your own question.