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();
}
Braiam
  • 1
  • 11
  • 47
  • 78
pepe
  • 9,799
  • 25
  • 110
  • 188

4 Answers4

705

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(' ');
Max Favilli
  • 6,161
  • 3
  • 42
  • 62
Dexter
  • 18,213
  • 4
  • 44
  • 54
  • thanks dexter this solution works perfectly for my needs – pepe Feb 02 '11 at 22:03
  • 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 '12 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 https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/replace, under the title `Specifying a function as a parameter` – Dexter Sep 01 '12 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 http://stackoverflow.com/questions/15150168/title-case-in-javascript-for-diacritics-non-ascii – BearCode Aug 26 '13 at 02: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 '15 at 20:10
  • 3
    DOESN'T work for non-english words. – Alexey Sh. Feb 26 '16 at 10:17
  • Shouldn't we not lowercase the substr(1) part of the string? You may want to omit that, or make it optional. – Joe Heyming Apr 11 '16 at 16:38
  • `substr(1).toLowerCase()` converts everything except for the first character in each word to lower case - it's needed for the exact example that the OP posted (cHIcaGO ==> Chicago). You can omit the `toLowerCase()` if you don't want to force the rest of the string to be lower case, but you need to keep in `substr(1)` otherwise you'll end up with only the first character in each word! – Dexter Apr 13 '16 at 01:46
  • would be nice if it didn't capitalize connecting words (and, for, this, that, etc.) as titles do not typically make these uppercase. – Cybernetic Aug 19 '17 at 17:03
  • It wont work with accents... like "Úrsula" – Tiago Gouvêa Sep 28 '17 at 14:12
  • 1
    Why using `\w`? It matches only ASCII chars (a-z, A-Z), but not for other languages. I used `/\.*\S*/g` as a regex and it seems to work fine for me. – Andrew Simontsev Mar 23 '18 at 12:31
  • This is my version based on @BearCode's link, compatible with diacritics, dashes, underscores, and single quotes. For example "gOOgle ångus OU_LIN ou'lin ou-lin" will be converted to "Google Ångus Ou_Lin Ou'Lin Ou-Lin": `function toTitleCase(str) { return str.toLowerCase().replace(/[^\s_'-]+/g, function (word) { return word.replace(/^./, function (firstLetter) { return firstLetter.toUpperCase(); }); }); }` – cprcrack Oct 06 '18 at 04:03
  • For ES6, it's an excellent use of reduce instead of map + join: text = text.split(' ').reduce((acc, cv) => { return acc + " " + cv[0].toUpperCase() + cv.slice(1); }, "").trim(); – Chayemor Jul 23 '19 at 10:17
  • es6 best solution – Tim Bogdanov Jun 14 '22 at 22:07
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";
capdragon
  • 14,565
  • 24
  • 107
  • 153
  • 2
    http://www.w3schools.com/css/pr_text_text-transform.asp – hunter Feb 02 '11 at 19:17
  • 2
    thanks capdragon - but i need city names to be changed on client side AND saved in the database as capitalized -- i don't think CSS would allow for that, does it? – pepe Feb 02 '11 at 19:40
  • 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 02 '11 at 21:05
  • 2
    css simply styles and renders, so you would still have to make sure the injected value is lowercased and first letter capped before inject into DB – KJYe.Name Feb 02 '11 at 21:49
  • please take a look at example i listed on my answer. – KJYe.Name Feb 02 '11 at 21:57
  • This does not work if the data is already uppercase – abiNerd Jul 17 '15 at 08:14
  • @capdragon, what I should have said was that 'capitalize' only changes the first letter to uppercase. So if your text is already in caps and you add 'capitalize' it just all stays in capital letters. Wish this wasn't the case but oh well :( http://www.w3schools.com/cssref/pr_text_text-transform.asp – abiNerd Jul 22 '15 at 08:49
  • 13
    Downvoted because the question specifies JavaScript and you gave a solution using a different technology. – Rik Smith-Unna Jan 06 '17 at 06: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 03 '17 at 19:57
  • 5
    downvote due to not answering using the OPs requested language – dtburgess Feb 21 '17 at 23:02
  • downvote as the question is asked for Javascript, not CSS. – Jeet Chaudhari Jul 20 '18 at 07:05
  • Downvoted because the original question asked for a JS solution, not CSS. – Matthew Campbell Oct 24 '18 at 16:47
  • 1
    Upvoted because this answer offers a solution that works well for me. – Michael Hays Aug 09 '19 at 01:09
  • 1
    for all the people who are hurt that the solution isnt in js. Here it is. document.getElementById("myP").style.textTransform = "capitalize"; – Kamal Reddy Aug 27 '19 at 06:41
26
function convertCase(str) {
  var lower = String(str).toLowerCase();
  return lower.replace(/(^| )(\w)/g, function(x) {
    return x.toUpperCase();
  });
}
maerics
  • 151,642
  • 46
  • 269
  • 291
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.

KJYe.Name
  • 16,969
  • 5
  • 48
  • 63
  • 3
    Seems fine, but do not add this to `String.prototype`. – Travis Webb Oct 03 '16 at 03: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() – user1071182 Mar 03 '17 at 04:01
  • 1
    It don't work with accents, like "Úrsula" – Tiago Gouvêa Sep 28 '17 at 14:19