769

Is there a simple way to convert a string to Title Case? E.g. john smith becomes John Smith. I'm not looking for something complicated like John Resig's solution, just (hopefully) some kind of one- or two-liner.

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
MDCore
  • 17,583
  • 8
  • 43
  • 48

69 Answers69

958

Try this:

function toTitleCase(str) {
  return str.replace(
    /\w\S*/g,
    function(txt) {
      return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    }
  );
}
<form>
  Input:
  <br /><textarea name="input" onchange="form.output.value=toTitleCase(this.value)" onkeyup="form.output.value=toTitleCase(this.value)"></textarea>
  <br />Output:
  <br /><textarea name="output" readonly onclick="select(this)"></textarea>
</form>
meyi
  • 7,574
  • 1
  • 15
  • 28
Greg Dean
  • 29,221
  • 14
  • 67
  • 78
  • 19
    Could anyone please explain, why `\w\S*` is used, instead of `\w+` or `\w*` for example? I don't know, why you would want to include anything but spaces and therefore change *Jim-Bob* to *Jim-bob*. – martinczerwi Jan 09 '13 at 09:17
  • 5
    @martinCzerwi the `\w\S*` also caused the `Jim-bob` problem on our end. Using `\w*` solved this. – Bouke Feb 27 '13 at 13:31
  • 15
    `/([^\W_]+[^\s-]*) */g` solves the `Jim-Bob` problem, ie: *`jim-bob`* `-->` *`Jim-Bob`* – recursion.ninja Jun 01 '13 at 18:55
  • Thank you for the code Greg, what does Pavel's comment mean here? Will this not be compatible with Firefox or IE? – Doug Molineux Aug 21 '13 at 20:00
  • 1
    @PeteHerbertPenito I'm guessing he tested it in Chrome 12 to find that it only worked with the Latin-1 character set. e.g. toTitleCase("ẁāšœ") -> "ẁāšœ" (still the same in Chrome 30) – Carson Myers Oct 30 '13 at 23:49
  • 27
    If the *`jim-bob` `-->` `Jim-Bob`* is your desire, you should probably do *`/\b\w+/g`*. Example: `str.replace(/\b\w+/g,function(s){return s.charAt(0).toUpperCase() + s.substr(1).toLowerCase();});` – vol7ron Jan 17 '14 at 17:20
  • 1
    How about strings with '_' e.g. 'hot_wheels'. How should the regex be modified to handle this? – SaurabhM Sep 08 '15 at 23:58
  • 2
    Keep it simple, `\b\w` – Avinash Raj Sep 09 '16 at 13:39
  • 8
    `\w\S*` is used instead of `\w+` or `\w*` so that words like `Don't` don't get modified to `Don'T`, but as others have pointed out `\w\S*` causes issues with hyphenated words. – doubleDown Feb 01 '17 at 14:59
  • 1
    What about names like John McDonald and such? Shouldn't eveything after the first letter be left untouched (not lowercased)? – SoluableNonagon Feb 07 '18 at 03:03
  • Like many answers here this breaks for single-char inputs: `toTitleCase('f')` – Madbreaks Sep 19 '18 at 17:57
  • Like many of the answers here, this does not work for (1) languages where title-casing does not affect only the first letter, and (2) scripts using supplemental code points. Just because it works for English doesn't mean it works in general. – sffc Feb 05 '19 at 18:17
  • Adding a second transformation to correct some edge cases like `Hawke's Bay`: `str .replace(/\b\w+/g, match => { return match.charAt(0).toUpperCase() + match.substr(1).toLowerCase(); }) .replace(/['’”‘“][A-Z]{1}\b/g, match => { return match.toLowercase(); });` – Adam Reis Jan 13 '20 at 09:56
  • 4
    `/\b\w+('\w{1})?/g` keeps `Don't` and `Jim-Bob` or `Inside/Outside`. Also omit the `toLowerCase()` to keep `McDonalds` as is. – eagor Jun 15 '20 at 14:42
  • 1
    This fails on "ØSTER HUS AS" giving "ØSter Hus As". – André C. Andersen Aug 10 '20 at 14:37
  • 1
    Why do some developers insist on changing the case or removing spaces in people's names? It's really aggravating when some app keeps forcing the case of my name to be wrong. I know how to write my own name! I end up editing the html or disabling JS just so my surname doesn't get completely mucked up. – Paul Feb 04 '21 at 16:54
  • I have come back to this page so many times, how does this not have more upvotes – garek007 Nov 22 '21 at 22:17
  • 1
    `substr` is now deprecated: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr. Not sure what the best replacement is but I went with `substring`. – Paul Mar 11 '22 at 18:48
  • 1
    more simple and fast `str.toLowerCase().replace(/\b\S/g, function(t) { return t.toUpperCase(); });` – dovid Jun 28 '22 at 01:15
  • @Paul, for this function it will be OK to use `slice()` instead of `substring()`. The difference is that slice move back when index is negative, but substring turn it to 0. – Marcelo Scofano Diniz Feb 01 '23 at 21:13
  • 1
    @dovid Your implementation fails with apostrophes (e.g. transforming `don't` into `Don'T`) because it does *not* consider them as word characters, since you are using the `/\b\S/g` regex which is equivalent to `/(?<!\w)(?=\w)\S/g` that is to `/(?<!\w)\w/g` (since `\w` is a subset of `\S`) which matches alphanumeric characters or underscores (`\w` is equivalent to `[A-Za-z0-9_]`) that are not preceded by alphanumeric characters or underscores (`\w`). A fix: `text.toLowerCase().replace(/(?<!\S)\S/g, initial => initial.toUpperCase())`. – Géry Ogam Apr 23 '23 at 23:36
  • Various methods benchmarked: https://jsbench.me/znli6mhkgr/1 – thdoan May 27 '23 at 23:41
  • This doesn’t work on ‘džungla’. – user3840170 Aug 31 '23 at 07:07
312

If a CSS solution meets your needs, you can apply the text-transform CSS style to your controls:

text-transform: capitalize;

Just be aware that this will transform:
hello world to Hello World
HELLO WORLD to HELLO WORLD (no change)
emily-jane o'brien to Emily-jane O'brien (incorrect)
Maria von Trapp to Maria Von Trapp (incorrect)

Michael
  • 8,362
  • 6
  • 61
  • 88
Talha Ashfaque
  • 3,656
  • 1
  • 15
  • 7
  • 65
    -1. This css works, but doesn't work as most people expect because if the text starts out as all caps, there is no effect. http://www.webmasterworld.com/forum83/7506.htm – whitneyland Aug 23 '11 at 17:37
  • 2
    @Akshar : A lowercase rule would be replaced by a title case rule. Since css doesn't modify the source content, the effect is that the lowercase rule is removed (leaving the source content in all caps) and then the titlecase rule would be applied (doing nothing). – dokkaebi Aug 15 '12 at 19:49
  • 72
    JS is used outside browsers. – mikemaccana Feb 05 '13 at 13:43
  • 13
    The question was: **"Is there a simple way to convert a string to title case?"**. This answer does not convert a string. This is a style applied atop a string. – kingPuppy Sep 06 '19 at 16:40
  • If you want data in your database to be clean, so that it can be used cleanly when passing to 3rd party services or exported to CSV, then CSS is not really an option. CSS is intended for cosmetics, and while it's grown a lot over the years and you can use it to solve these kind of problems, the solution remains cosmetic and it doesn't solve the underlying problem. – Adam Reis Jan 13 '20 at 09:53
  • 17
    +1 The question is vague and doesn't explain the use case. Maybe they had in mind converting the string with JS, but actually CSS works better for them, as is my case. – Christian Sirolli Apr 10 '20 at 04:41
  • 2
    Get in the bin, "JavaScript" is literally in the question. – Iest Apr 24 '20 at 19:06
  • If you are going to display the text in the browser, this is the best solution because it handles Unicode, which none of the other answers address. – Minas Mina Dec 20 '20 at 10:24
  • 1
    With 442,000 views, we are about as far as you can get from the argument "Not what OP wanted" being valid IMO. – yeah22 Mar 30 '21 at 08:10
  • @AdamReis - not sure I agree with the premise. IF you want your data in your database to be "clean" then you probably want it _as entered_, since any operation on the data loses some of the original intention (see the Maria von Trapp example above). So CSS is absolutely the right way to go in some cases. – Algy Taylor Sep 07 '21 at 08:41
  • 1
    @AlgyTaylor Always interesting to receive a reply on a 7 year old comment :) If CSS works for you, then go for it. We use it on a case by case basis, and we do not always want data "as entered" by users, because there are clowns out there that do not know how to disable their CAPS LOCK. – Adam Reis Sep 10 '21 at 02:08
  • this could be another way. Bbut not reflectoing the question. – infomasud Nov 05 '21 at 10:24
  • This is the only answer that covers Unicode code points that have a title-case variant, like the digraph "dž", which should be converted to "Dž" in title case, but the JavaScript code would have converted it incorrectly to "DŽ". – Attila O. Jun 19 '22 at 11:36
  • I think judging that at least 305 people found this answer useful, everyone can stop moaning as obviously many people have been helped by this answer – Lushawn Jun 01 '23 at 18:39
233

A slightly more elegant way, adapting Greg Dean's function:

String.prototype.toProperCase = function () {
    return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
};

Call it like:

"pascal".toProperCase();
Tuan
  • 5,382
  • 1
  • 22
  • 17
  • 5
    Keep in mind if you have a user with a dash in their name and they enter `Jo-Ann Smith`, this code will convert them to `Jo-ann Smith` (note the lowercase `a` in `Ann`). – dbau Apr 07 '12 at 11:23
  • 20
    @daniellmb Why should he not alter the String prototype? I think it is a good solution. Think of ruby open classes, it is perfectly valid to add functions to existing classes and it is widely accepted. – marco-fiset Sep 21 '12 at 15:31
  • 117
    @marco-fiset Because it doesn't play well with others! Bad things happen when you have 2 libraries that are both trying to modify native JavaScript objects with incompatible changes. Imagine if jQuery and Google Maps followed this design pattern, you couldn't have both on the same page. – SavoryBytes Sep 21 '12 at 17:28
  • 6
    @daniellmb An excellent point. Prefixing the method name should help avoid this, as will making the method non-enumerable. – mikemaccana Feb 05 '13 at 13:42
  • 71
    I feel like the "don't modify native JavaScript objects" statement is just like "never use goto" or "eval is evil". There are plenty of cases where it is ok. If you have complete control over your project and of course don't plan on releasing it as a library, I see no problems with this method. – FoxMulder900 Jun 23 '15 at 09:15
  • Here is why you don't extend native objects: http://eslint.org/docs/rules/no-extend-native – brandonscript Jun 27 '16 at 21:02
  • For some reason this does not capitalize the second word of my sentences – Kyle Hotchkiss Oct 04 '16 at 21:43
  • 1
    Like many answers here this breaks for single-char inputs: `'f'.toProperCase` – Madbreaks Sep 19 '18 at 17:56
  • This doesn’t work on ‘džungla’. – user3840170 Aug 31 '23 at 07:10
183

Here's my version, IMO it's easy to understand and elegant too.

const str = "foo bar baz";
const newStr = str.split(' ')
   .map(w => w[0].toUpperCase() + w.substring(1).toLowerCase())
   .join(' ');
console.log(newStr);
xinthose
  • 3,213
  • 3
  • 40
  • 59
a8m
  • 9,334
  • 4
  • 37
  • 40
  • 3
    Alternatively, you can lowercase the substring in the mapping: ```str.split(' ').map(i => i[0].toUpperCase() + i.substring(1).toLowerCase()).join(' ')``` – Dave Land Aug 15 '16 at 16:39
  • 9
    I disagree with calling `.toLowerCase()`. Names such as "McDonald" or acronyms like "ASAP" should retain their uppercase characters. If someone actually passed in a string like "heLLO", the application shouldn't assume the uppercase letters are incorrect. – Thomas Higginbotham Feb 01 '17 at 18:22
  • 1
    @ThomasHigginbotham How about this? `String.prototype.toTitleCase = function (blnForceLower) { var strReturn; (blnForceLower ? strReturn = this.toLowerCase() : strReturn = this); return strReturn .split(' ') .map(i => i[0].toUpperCase() + i.substr(1)) .join(' '); }` – Sean Kendle Feb 02 '17 at 16:26
  • Yes, providing an option to force lowercase would be preferred. – Thomas Higginbotham Feb 02 '17 at 16:43
  • Yes, this is easy to understand, but when I try it, it doesn't actually capitalize anything (for some reason). – Katinka Hesselink Dec 07 '17 at 08:25
  • 3
    This will break if `str` is a single character. – Madbreaks Sep 19 '18 at 17:52
  • This will break if str contains sequential spaces – Gove Oct 23 '20 at 22:37
  • 2
    This looks like this is [the fastest solution](https://stackoverflow.com/a/64910248/6320039) :) – Ulysse BN Nov 19 '20 at 10:57
  • To avoid out-of bound errors for single character strings I suppose the following would do inside the map expression... `w[0].toUpperCase() + w.length > 1 ? w.substr(1).toLowerCase() : ''` – rey_coder Apr 22 '21 at 16:08
  • This doesn’t work on ‘džungla’. – user3840170 Aug 31 '23 at 07:11
121

Here’s my function that converts to title case but also preserves defined acronyms as uppercase and minor words as lowercase:

String.prototype.toTitleCase = function() {
  var i, j, str, lowers, uppers;
  str = this.replace(/([^\W_]+[^\s-]*) */g, function(txt) {
    return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
  });

  // Certain minor words should be left lowercase unless 
  // they are the first or last words in the string
  lowers = ['A', 'An', 'The', 'And', 'But', 'Or', 'For', 'Nor', 'As', 'At', 
  'By', 'For', 'From', 'In', 'Into', 'Near', 'Of', 'On', 'Onto', 'To', 'With'];
  for (i = 0, j = lowers.length; i < j; i++)
    str = str.replace(new RegExp('\\s' + lowers[i] + '\\s', 'g'), 
      function(txt) {
        return txt.toLowerCase();
      });

  // Certain words such as initialisms or acronyms should be left uppercase
  uppers = ['Id', 'Tv'];
  for (i = 0, j = uppers.length; i < j; i++)
    str = str.replace(new RegExp('\\b' + uppers[i] + '\\b', 'g'), 
      uppers[i].toUpperCase());

  return str;
}

For example:

"TO LOGIN TO THIS SITE and watch tv, please enter a valid id:".toTitleCase();
// Returns: "To Login to This Site and Watch TV, Please Enter a Valid ID:"
Geoffrey Booth
  • 7,168
  • 5
  • 35
  • 42
  • 1
    I liked yours, I also encounter problems when dealing with roman numbers... just patched it with I, II, III, IV, etc. – Marcelo Aug 21 '11 at 00:19
  • Hyphenated words should be capitalized. With your function `JIM-BOB` does not go to `Jim-Bob` it instead goes to `Jim-bob` – recursion.ninja Jun 01 '13 at 17:21
  • 2
    Fixed. The regex in the third line has been changed from `/\w\S*/g` to `/([^\W_]+[^\s-]*) */g` per @awashburn's comment above to address this. – Geoffrey Booth Jun 04 '13 at 15:49
  • 2
    Is there an advantage to be gained by using your regex pattern over [`/\b\w+/g`](http://stackoverflow.com/questions/196972/convert-string-to-title-case-with-javascript#comment31909172_196991), which I find to be more quickly comprehensible? – Michael May 27 '14 at 21:14
  • 2
    Not that I can see, I was simply taking another commenter’s suggestion to solve the hyphenated-word problem; but your regex appears to do just as well, and simplicity is always better. For posterity and future visitors to this post, I just changed the regex in the third line from `/([^\W_]+[^\s-]*) */g` to `/\b\w+/g` per @Michael’s comment; please comment if you find a case where the more-complicated regex is necessary. – Geoffrey Booth May 28 '14 at 14:30
  • 1
    I changed the 3rd line regex to `/\b[\w-\']+/g` in order to allow hyphenated words and apostrophe in words. – Shamasis Bhattacharya Jul 03 '14 at 14:48
  • 1
    The apostrophe case seems to be why `/([^\W_]+[^\s-]*) */g` was so complicated; it also handles curly quotes correctly, which `/\b[\w-\']+/g` does not, so I’m going back to `/([^\W_]+[^\s-]*) */g`. It handles hyphenated words correctly too. – Geoffrey Booth Jul 04 '14 at 00:30
  • 1
    Excellent. This helped me. Have change regex to /([^\W_]+[^\s-\.]*) */g to convert abbreviations with dot to upper case like i.b.m. Had words which contain '&', so added '&Amp;' to lowers. – Sudarshan_SMD Jul 31 '14 at 13:49
  • 1
    To remind us that language is messy, there is the Freudian id which is not written in all uppers. Unless you're shouting, which is such an id thing to do. – tylertrotter Dec 17 '18 at 14:44
  • This doesn't work for a title such as "Revelation: The Seven Bowls", but overall pretty great. – PRMan Dec 14 '20 at 20:43
59

I prefer the following over the other answers. It matches only the first letter of each word and capitalises it. Simpler code, easier to read and less bytes. It preserves existing capital letters to prevent distorting acronyms. However you can always call toLowerCase() on your string first.

function title(str) {
  return str.replace(/(^|\s)\S/g, function(t) { return t.toUpperCase() });
}

You can add this to your string prototype which will allow you to 'my string'.toTitle() as follows:

String.prototype.toTitle = function() {
  return this.replace(/(^|\s)\S/g, function(t) { return t.toUpperCase() });
}

Example:

String.prototype.toTitle = function() {
  return this.replace(/(^|\s)\S/g, function(t) { return t.toUpperCase() });
}

console.log('all lower case ->','all lower case'.toTitle());
console.log('ALL UPPER CASE ->','ALL UPPER CASE'.toTitle());
console.log("I'm a little teapot ->","I'm a little teapot".toTitle());
Tom Kay
  • 1,512
  • 15
  • 25
  • 6
    It's even nicer as a lambda `const titleCase = (str) => str.replace(/\b\S/g, t => t.toUpperCase());` – 0xcaff Mar 04 '18 at 16:15
  • I didn't want to break IE, but yeah if the application is not legacy browser sensitive it could be shorter. – Tom Kay Mar 05 '18 at 15:47
  • This is only a partial solution - op asked for how to convert a string to title case. This answer doesn't accomplish that for inputs like `NoT qUiITe`. – Madbreaks Sep 18 '18 at 17:36
  • @Madbreaks The question did not stipulate that mixed case inputs should be converted. However, i have updated the answer mentioning `toLowerCase`. Just be aware that it would break acronyms. `an HTML document`: `An HTML Document` vs `An Html Document` – Tom Kay Sep 19 '18 at 10:22
  • But "title case" has meaning. A sentence that is all caps would not reasonably be considered title case and your answer allows for that. https://en.wikipedia.org/wiki/Letter_case#Title_case - I do like your answer but in this context it's incomplete. – Madbreaks Sep 19 '18 at 14:45
  • 6
    @Madbreaks While your initial example was contrived, you make a good point in stating that the output would be unchanged if the input were capitalised. That being said, I feel the answer as-is (with the edit suggesting `toLowerCase`) is more flexible/useful than one which assumes the developers intentions. This method also reflects the functionality of similar built-in methods of other languages such as PHP (`ucwords`) and Golang (`strings.Title`). .NET (`TextInfo.ToTitleCase`) interestingly works for mixed case, but would also leave fully capitalised strings unchanged. – Tom Kay Sep 19 '18 at 16:16
  • Thanks - I didn't catch your edit adding `toLowerCase` which is good enough for me. +1, cheers – Madbreaks Sep 19 '18 at 17:50
  • Unfortunately `\b` doesn't quite do what you expect with words containing apostrophes. `title("I'm a little teapot") => "I'M A Little Teapot"` – rcoup Sep 26 '18 at 14:23
  • thanks for the feedback @rcoup - if i switch it to match (whitespace or start of line), can you think of any backward-compatibility issues compared to boundary? – Tom Kay Sep 26 '18 at 14:32
  • @TomKay sentences/commas/semicolon/hyphens would be a problem. – rcoup Oct 01 '18 at 13:44
54

You could immediately toLowerCase the string, and then just toUpperCase the first letter of each word. Becomes a very simple 1 liner:

function titleCase(str) {
  return str.toLowerCase().replace(/\b\w/g, s => s.toUpperCase());
}

console.log(titleCase('iron man'));
console.log(titleCase('iNcrEdible hulK'));
KevBot
  • 17,900
  • 5
  • 50
  • 68
  • I like this solution; nice and simple. It looks like a bit of CoffeeScript slipped into your answer though (`s => s.toUpperCase()`). My variant is to do what you have done, but extending the String object (as controversial as that is): `Object.defineProperty(String.prototype, '_toProperCase', {value:function() {return this.toLowerCase().replace(/\b(\w)/g, function(t) {return t.toUpperCase()})}})` – Waz Apr 21 '17 at 09:14
  • 1
    @Waz, thanks for the ideas! Just wanted to clarify on the `=>`, that is a [native arrow function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) (ES6), the link jumps to the Mozillla Docs on them which also provides a support table. – KevBot Apr 21 '17 at 15:27
  • Thanks a lot...looking for something short and precise – Partha Paul Dec 06 '20 at 21:04
  • 2
    `string => string.toLowerCase().replace(/\b\w/g, word_head => word_head.toUpperCase());`. No need to group the `\w`; what is being replaced is a `\b\w` where `\b` is not a string. – Константин Ван May 27 '22 at 18:13
  • 1
    as @КонстантинВан remarked, without group the solution is much faster – dovid Jun 28 '22 at 10:36
  • 1
    @КонстантинВан, and dovid, thanks for the feedback! I've implemented your suggestion. I took a look at some benchmarks for the difference, and you're correct, it is much faster. – KevBot Jun 28 '22 at 19:49
  • One thing to watch out for here is strings such as "rachael's tasks" result in a false positive match on the first "s" and will capitalize it inappropriately. So for some needs, unable to use the above technique as it only works for simple cases. Alternatively @Ulysse BN's answer does work in these instances, FYI. – sean2078 Jan 03 '23 at 17:37
  • I'm not an expert on this, but there is also `s.toLocaleUpperCase()` which may produce better results in other languages. – hostingutilities.com Jul 01 '23 at 17:50
36

Benchmark

TL;DR

The winner of this benchmark is the plain old for loop:

function titleize(str) {
    let upper = true
    let newStr = ""
    for (let i = 0, l = str.length; i < l; i++) {
        // Note that you can also check for all kinds of spaces  with
        // str[i].match(/\s/)
        if (str[i] == " ") {
            upper = true
            newStr += str[i]
            continue
        }
        newStr += upper ? str[i].toUpperCase() : str[i].toLowerCase()
        upper = false
    }
    return newStr
}
// NOTE: you could beat that using charcode and string builder I guess.

Details

I've taken the most popular and distinct answers and made a benchmark with those.

Here's the result on my MacBook pro:

enter image description here

And for completeness, here are the functions used:

str = "the QUICK BrOWn Fox jUMPS oVeR the LAzy doG";
function regex(str) {
  return str.replace(
    /\w\S*/g,
    function(txt) {
      return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    }
  );
}

function split(str) {
  return str.
    split(' ').
    map(w => w[0].toUpperCase() + w.substr(1).toLowerCase()).
    join(' ');
}

function complete(str) {
  var i, j, str, lowers, uppers;
  str = str.replace(/([^\W_]+[^\s-]*) */g, function(txt) {
    return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
  });

  // Certain minor words should be left lowercase unless 
  // they are the first or last words in the string
  lowers = ['A', 'An', 'The', 'And', 'But', 'Or', 'For', 'Nor', 'As', 'At', 
  'By', 'For', 'From', 'In', 'Into', 'Near', 'Of', 'On', 'Onto', 'To', 'With'];
  for (i = 0, j = lowers.length; i < j; i++)
    str = str.replace(new RegExp('\\s' + lowers[i] + '\\s', 'g'), 
      function(txt) {
        return txt.toLowerCase();
      });

  // Certain words such as initialisms or acronyms should be left uppercase
  uppers = ['Id', 'Tv'];
  for (i = 0, j = uppers.length; i < j; i++)
    str = str.replace(new RegExp('\\b' + uppers[i] + '\\b', 'g'), 
      uppers[i].toUpperCase());

  return str;
}

function firstLetterOnly(str) {
  return str.replace(/\b(\S)/g, function(t) { return t.toUpperCase(); });
}

function forLoop(str) {
  let upper = true;
  let newStr = "";
  for (let i = 0, l = str.length; i < l; i++) {
    if (str[i] == " ") {
      upper = true;
        newStr += " ";
      continue;
    }
    newStr += upper ? str[i].toUpperCase() : str[i].toLowerCase();
    upper = false;
  }
  return newStr;
}

Note that i deliberately did not change the prototype since I consider it a really bad practice and I don't think we should promote such practice in our answers. This is only ok for small codebases when you're the only one working on it.

If you want to add any other way to do it to this benchmark, please comment a link to the answer !


EDIT 2022 Mac M1: On my new computer, with more recent chrome, split wins. If you really care about performance on a specific machine you should run the benchmark yourself

Ulysse BN
  • 10,116
  • 7
  • 54
  • 82
  • 1
    The parentheses group in the method of 'first letter only' are not consumed, and if you remove them then this method defeats the regex method, as it makes sense. – dovid Jun 28 '22 at 01:11
  • 1
    and `str.toLowerCase().replace(/\b\S/g, function(t) { return t.toUpperCase(); });` also win 'regex' method and achieves the same result – dovid Jun 28 '22 at 01:14
  • Dramatic improvement of `complete` method: https://jsben.ch/yTK3Y – dovid Jun 28 '22 at 02:01
  • 1
    @dovid I'll have to admit that I aggregated other answers directly in the benchmark. Hence feel free to edit my answer, and I'd suggest you to also comment directly on the concerned answers :) – Ulysse BN Jun 28 '22 at 07:47
26

var result =
  'this is very interesting'.replace(/\b[a-z]/g, (x) => x.toUpperCase())

console.log(result) // This Is Very Interesting
simo
  • 15,078
  • 7
  • 45
  • 59
  • Just a question, the () construct is for specifying a match on any of a sequence of options: that is, (a|b) matches a or b. What does the construction (.) do? – Michael Blackburn Dec 30 '14 at 21:17
  • For anyone who had the same question, it defines a replacement "blob" which is used in the replacement section. The blobs are numbered sequentially, the first () is put into $1, the second into $2. I found this site useful: http://javascript.info/tutorial/regular-expressions-methods – Michael Blackburn Dec 30 '14 at 21:34
  • I am not able to get the above to work, but I'm far from a regex wizard. I'm using `'string'.replace(/^(.)(.*)/,function(s,p1,p2){return p1.toUpperCase()+p2;})` Again, this only works for capitalizing the first letter of a string, but in case that's what you need, my construction works. – Michael Blackburn Dec 30 '14 at 21:39
  • 1
    For some reason FF35 seems to choke on `'$1'.toUpperCase()`, seems the uppercase hasn't been done by the time the value is assigned. Worked around by using function `'string'.replace(/^(.){1}/,function(match) { return match.toUpperCase(); })` – MrYellow Jan 25 '15 at 23:20
  • Hi All, the answer is fixed! I'm pretty sure it was working by the time I initially posted it. Anyway thanks for the input! – simo May 18 '16 at 12:28
  • This doesn’t work on ‘džungla’. – user3840170 Aug 31 '23 at 07:13
24

Surprised to see no one mentioned the use of rest parameter. Here is a simple one liner that uses ES6 Rest parameters.

let str="john smith"
str=str.split(" ").map(([firstChar,...rest])=>firstChar.toUpperCase()+rest.join("").toLowerCase()).join(" ")
console.log(str)
kapil pandey
  • 1,853
  • 1
  • 13
  • 26
  • I appreciate this solution and have decided that this is the best code for my intended use. I have noticed that it **does not consider the use of a hyphen** in names. This does not greatly impact my current use; however, **I am wondering how this code might be adjusted for that consideration**. Thanks again for a solid solution! – Paul Murray Oct 05 '22 at 16:43
  • This implementation is equivalent to the Python function [`string.capwords(s, sep=None)`](https://docs.python.org/3/library/string.html#string.capwords). – Géry Ogam Apr 23 '23 at 22:39
21

Without using regex just for reference:

String.prototype.toProperCase = function() {
  var words = this.split(' ');
  var results = [];
  for (var i = 0; i < words.length; i++) {
    var letter = words[i].charAt(0).toUpperCase();
    results.push(letter + words[i].slice(1));
  }
  return results.join(' ');
};

console.log(
  'john smith'.toProperCase()
)
adiga
  • 34,372
  • 9
  • 61
  • 83
Mike
  • 435
  • 3
  • 6
18

Just in case you are worried about those filler words, you can always just tell the function what not to capitalize.

/**
 * @param String str The text to be converted to titleCase.
 * @param Array glue the words to leave in lowercase. 
 */
var titleCase = function(str, glue){
    glue = (glue) ? glue : ['of', 'for', 'and'];
    return str.replace(/(\w)(\w*)/g, function(_, i, r){
        var j = i.toUpperCase() + (r != null ? r : "");
        return (glue.indexOf(j.toLowerCase())<0)?j:j.toLowerCase();
    });
};

Hope this helps you out.

edit

If you want to handle leading glue words, you can keep track of this w/ one more variable:

var titleCase = function(str, glue){
    glue = !!glue ? glue : ['of', 'for', 'and', 'a'];
    var first = true;
    return str.replace(/(\w)(\w*)/g, function(_, i, r) {
        var j = i.toUpperCase() + (r != null ? r : '').toLowerCase();
        var result = ((glue.indexOf(j.toLowerCase()) < 0) || first) ? j : j.toLowerCase();
        first = false;
        return result;
    });
};
fncomp
  • 6,040
  • 3
  • 33
  • 42
  • 2
    You can explode a string into an array. So we could have portuguese, spanish, italian and french prepositions: `glue ='de|da|del|dos|do|das|des|la|della|delli'.split('|');` – Junior Mayhé Jun 25 '12 at 23:58
  • This won't ensure capitalization of the first word; ie `and another thing` becomes `and Another Thing`. Just need an elegant way to always capitalize the first word. – Brad Koch Apr 30 '13 at 14:41
  • @BradKoch - pad with spaces so you're using ' and ', ' de ', etc. as the search word, then 'And Another And Another' will replace to 'And Another and Another'. – Yimin Rong Sep 04 '15 at 13:19
  • good except it capitalizes also text after ' and - like H'Dy or Number-One – luky Jul 13 '19 at 14:41
  • Instead of using a ternary operator you could just use a fallback: glue = glue || ['of', 'for', 'and', 'a']; – tm2josep Nov 07 '19 at 14:42
  • @tm2josep yeah, I was writing in the way Crockford recommends when I answered this question :-) It's been 6yrs on the day, but I still prefer explicit coercing the types. – fncomp Nov 13 '19 at 19:50
17

If you need a grammatically correct answer:

This answer takes into account prepositions such as "of", "from", .. The output will generate an editorial style title you would expect to see in a paper.

toTitleCase Function

The function that takes into account grammar rules listed here. The function also consolidates whitespace and removes special characters (modify regex for your needs)

const toTitleCase = (str) => {
  const articles = ['a', 'an', 'the'];
  const conjunctions = ['for', 'and', 'nor', 'but', 'or', 'yet', 'so'];
  const prepositions = [
    'with', 'at', 'from', 'into','upon', 'of', 'to', 'in', 'for',
    'on', 'by', 'like', 'over', 'plus', 'but', 'up', 'down', 'off', 'near'
  ];

  // The list of spacial characters can be tweaked here
  const replaceCharsWithSpace = (str) => str.replace(/[^0-9a-z&/\\]/gi, ' ').replace(/(\s\s+)/gi, ' ');
  const capitalizeFirstLetter = (str) => str.charAt(0).toUpperCase() + str.substr(1);
  const normalizeStr = (str) => str.toLowerCase().trim();
  const shouldCapitalize = (word, fullWordList, posWithinStr) => {
    if ((posWithinStr == 0) || (posWithinStr == fullWordList.length - 1)) {
      return true;
    }

    return !(articles.includes(word) || conjunctions.includes(word) || prepositions.includes(word));
  }

  str = replaceCharsWithSpace(str);
  str = normalizeStr(str);

  let words = str.split(' ');
  if (words.length <= 2) { // Strings less than 3 words long should always have first words capitalized
    words = words.map(w => capitalizeFirstLetter(w));
  }
  else {
    for (let i = 0; i < words.length; i++) {
      words[i] = (shouldCapitalize(words[i], words, i) ? capitalizeFirstLetter(words[i], words, i) : words[i]);
    }
  }

  return words.join(' ');
}

Unit Tests to Ensure Correctness

import { expect } from 'chai';
import { toTitleCase } from '../../src/lib/stringHelper';

describe('toTitleCase', () => {
  it('Capitalizes first letter of each word irrespective of articles, conjunctions or prepositions if string is no greater than two words long', function(){
    expect(toTitleCase('the dog')).to.equal('The Dog'); // Capitalize articles when only two words long
    expect(toTitleCase('for all')).to.equal('For All'); // Capitalize conjunctions when only two words long
    expect(toTitleCase('with cats')).to.equal('With Cats'); // Capitalize prepositions when only two words long
  });

  it('Always capitalize first and last words in a string irrespective of articles, conjunctions or prepositions', function(){
    expect(toTitleCase('the beautiful dog')).to.equal('The Beautiful Dog');
    expect(toTitleCase('for all the deadly ninjas, be it so')).to.equal('For All the Deadly Ninjas Be It So');
    expect(toTitleCase('with cats and dogs we are near')).to.equal('With Cats and Dogs We Are Near');
  });

  it('Replace special characters with space', function(){
    expect(toTitleCase('[wolves & lions]: be careful')).to.equal('Wolves & Lions Be Careful');
    expect(toTitleCase('wolves & lions, be careful')).to.equal('Wolves & Lions Be Careful');
  });

  it('Trim whitespace at beginning and end', function(){
    expect(toTitleCase(' mario & Luigi superstar saga ')).to.equal('Mario & Luigi Superstar Saga');
  });

  it('articles, conjunctions and prepositions should not be capitalized in strings of 3+ words', function(){
    expect(toTitleCase('The wolf and the lion: a tale of two like animals')).to.equal('The Wolf and the Lion a Tale of Two like Animals');
    expect(toTitleCase('the  three Musketeers  And plus ')).to.equal('The Three Musketeers and Plus');
  });
});

Please note that I am removing quite a bit of special characters from the strings provided. You will need to tweak the regex to address the requirements of your project.

dipole_moment
  • 5,266
  • 4
  • 39
  • 55
14

If regex used in the above solutions is getting you confused, try this code:

function titleCase(str) {
  return str.split(' ').map(function(val){ 
    return val.charAt(0).toUpperCase() + val.substr(1).toLowerCase();
  }).join(' ');
}
immazharkhan
  • 395
  • 2
  • 12
13

I made this function which can handle last names (so it's not title case) such as "McDonald" or "MacDonald" or "O'Toole" or "D'Orazio". It doesn't however handle German or Dutch names with "van" or "von" which are often in lower-case... I believe "de" is often lower-case too such as "Robert de Niro". These would still have to be addressed.

function toProperCase(s)
{
  return s.toLowerCase().replace( /\b((m)(a?c))?(\w)/g,
          function($1, $2, $3, $4, $5) { if($2){return $3.toUpperCase()+$4+$5.toUpperCase();} return $1.toUpperCase(); });
}
Lwangaman
  • 139
  • 1
  • 2
  • 1
    +1 for name awareness. Does not handle "macy" correctly, either, though. – brianary Jun 26 '13 at 00:35
  • This was the only function that correctly handled transforming uppercase and lower case to the correct case and that noticed initials like "U.S. Virgin Islands". – Rodrigo Polo Aug 06 '16 at 06:15
  • You can get around the `macy` problem by putting a negative lookahead in there so `\b((m)(a?c))?(\w)` becomes `\b((m)(a?c))?(\w)(?!\s)` – Ste Nov 08 '19 at 14:53
11

If you can use third party libraries in your code then lodash has a helper function for us.

https://lodash.com/docs/4.17.3#startCase

_.startCase('foo bar');
// => 'Foo Bar'

_.startCase('--foo-bar--');
// => 'Foo Bar'
 
_.startCase('fooBar');
// => 'Foo Bar'
 
_.startCase('__FOO_BAR__');
// => 'FOO BAR'
waqas
  • 4,357
  • 3
  • 34
  • 42
11

First, convert your string into array by splitting it by spaces:

var words = str.split(' ');

Then use array.map to create a new array containing the capitalized words.

var capitalized = words.map(function(word) {
    return word.charAt(0).toUpperCase() + word.substring(1, word.length);
});

Then join the new array with spaces:

capitalized.join(" ");

function titleCase(str) {
  str = str.toLowerCase(); //ensure the HeLlo will become Hello at the end
  var words = str.split(" ");

  var capitalized = words.map(function(word) {
    return word.charAt(0).toUpperCase() + word.substring(1, word.length);
  });
  return capitalized.join(" ");
}

console.log(titleCase("I'm a little tea pot"));

NOTE:

This of course has a drawback. This will only capitalize the first letter of every word. By word, this means that it treats every string separated by spaces as 1 word.

Supposedly you have:

str = "I'm a little/small tea pot";

This will produce

I'm A Little/small Tea Pot

compared to the expected

I'm A Little/Small Tea Pot

In that case, using Regex and .replace will do the trick:

with ES6:

const capitalize = str => str.length
  ? str[0].toUpperCase() +
    str.slice(1).toLowerCase()
  : '';

const escape = str => str.replace(/./g, c => `\\${c}`);
const titleCase = (sentence, seps = ' _-/') => {
  let wordPattern = new RegExp(`[^${escape(seps)}]+`, 'g');
  
  return sentence.replace(wordPattern, capitalize);
};
console.log( titleCase("I'm a little/small tea pot.") );

or without ES6:

function capitalize(str) {
  return str.charAt(0).toUpperCase() + str.substring(1, str.length).toLowerCase();
}

function titleCase(str) {
  return str.replace(/[^\ \/\-\_]+/g, capitalize);
}

console.log(titleCase("I'm a little/small tea pot."));
xGeo
  • 2,149
  • 2
  • 18
  • 39
10

ES 6

str.split(' ')
   .map(s => s.slice(0, 1).toUpperCase() + s.slice(1).toLowerCase())
   .join(' ')

else

str.split(' ').map(function (s) {
    return s.slice(0, 1).toUpperCase() + s.slice(1).toLowerCase();
}).join(' ')
Steve Bennett
  • 114,604
  • 39
  • 168
  • 219
jssridhar
  • 458
  • 4
  • 10
9

Most of these answers seem to ignore the possibility of using the word boundary metacharacter (\b). A shorter version of Greg Dean's answer utilizing it:

function toTitleCase(str)
{
    return str.replace(/\b\w/g, function (txt) { return txt.toUpperCase(); });
}

Works for hyphenated names like Jim-Bob too.

lewax00
  • 188
  • 1
  • 8
  • 2
    Is an elegant partial solution but does not work with accent or upper case strings. I get "Sofía Vergara" => "SofíA Vergara" or "Sofía VERGARA" => "SofíA VERGARA". The second case could be solved with apply .toLowerCase() function before .replace(...). The first case needs to find a right regular expression. – Asereware Sep 30 '14 at 18:31
  • 2
    Hmm, that seems like a bug in the regex implementation, I would think accented characters should be word characters (you are correct though, as-is it doesn't work for those cases). – lewax00 Oct 01 '14 at 23:20
  • `\w` only includes the characters `[A-Za-z0-9_]`, not all letters. For that you'd need to use the Unicode category `\p{L}`. You'll need the `/u` modifier (see [here](https://stackoverflow.com/questions/280712/javascript-unicode-regexes)) and a different solution for `\b`, which only works between `\W` and `\w` (see [here](https://stackoverflow.com/questions/10590098/javascript-regexp-word-boundaries-unicode-characters)) – cmbuckley Nov 13 '19 at 00:16
8
var toMatch = "john w. smith";
var result = toMatch.replace(/(\w)(\w*)/g, function (_, i, r) {
      return i.toUpperCase() + (r != null ? r : "");
    }
)

Seems to work... Tested with the above, "the quick-brown, fox? /jumps/ ^over^ the ¡lazy! dog..." and "C:/program files/some vendor/their 2nd application/a file1.txt".

If you want 2Nd instead of 2nd, you can change to /([a-z])(\w*)/g.

The first form can be simplified as:

function toTitleCase(toTransform) {
  return toTransform.replace(/\b([a-z])/g, function (_, initial) {
      return initial.toUpperCase();
  });
}
PhiLho
  • 40,535
  • 6
  • 96
  • 134
8

Try this, shortest way:

str.replace(/(^[a-z])|(\s+[a-z])/g, txt => txt.toUpperCase());
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
Vikram
  • 622
  • 1
  • 6
  • 18
  • This is sweet. For the basic use case I have (where performance isn't necessarily a priority) this works perfect! – KhoPhi Jul 13 '21 at 11:06
6

Use /\S+/g to support diacritics:

function toTitleCase(str) {
  return str.replace(/\S+/g, str => str.charAt(0).toUpperCase() + str.substr(1).toLowerCase());
}

console.log(toTitleCase("a city named örebro")); // A City Named Örebro

However: "sunshine (yellow)" ⇒ "Sunshine (yellow)"

le_m
  • 19,302
  • 9
  • 64
  • 74
6
"john f. kennedy".replace(/\b\S/g, t => t.toUpperCase())
Proximo
  • 6,235
  • 11
  • 49
  • 67
  • 2
    Works for the sample and `o'henry`, but does weird stuff with `horse's mouth`. – Michael Jun 24 '19 at 17:46
  • `"john f. kennEdy".toLowerCase().replace(/\b\S/g, t => t.toUpperCase())` better – w3debugger Feb 06 '20 at 22:28
  • Didn’t want to edit @Proximo’s answer: the `\b` and `\S` are special [character classes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes) denoting “word boundary” and “single, non-whitespace character. So, the regex matches every single character following a word boundary, and capitalizes that character by applying the given arrow function. – Jens Feb 28 '20 at 11:14
5

Try this

String.prototype.toProperCase = function(){
    return this.toLowerCase().replace(/(^[a-z]| [a-z]|-[a-z])/g, 
        function($1){
            return $1.toUpperCase();
        }
    );
};

Example

var str = 'john smith';
str.toProperCase();
Maxi Baez
  • 578
  • 5
  • 13
5

Here is my function that is taking care of accented characters (important for french !) and that can switch on/off the handling of lowers exceptions. Hope that helps.

String.prototype.titlecase = function(lang, withLowers = false) {
    var i, string, lowers, uppers;

    string = this.replace(/([^\s:\-'])([^\s:\-']*)/g, function(txt) {
        return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    }).replace(/Mc(.)/g, function(match, next) {
        return 'Mc' + next.toUpperCase();
    });

    if (withLowers) {
        if (lang == 'EN') {
            lowers = ['A', 'An', 'The', 'At', 'By', 'For', 'In', 'Of', 'On', 'To', 'Up', 'And', 'As', 'But', 'Or', 'Nor', 'Not'];
        }
        else {
            lowers = ['Un', 'Une', 'Le', 'La', 'Les', 'Du', 'De', 'Des', 'À', 'Au', 'Aux', 'Par', 'Pour', 'Dans', 'Sur', 'Et', 'Comme', 'Mais', 'Ou', 'Où', 'Ne', 'Ni', 'Pas'];
        }
        for (i = 0; i < lowers.length; i++) {
            string = string.replace(new RegExp('\\s' + lowers[i] + '\\s', 'g'), function(txt) {
                return txt.toLowerCase();
            });
        }
    }

    uppers = ['Id', 'R&d'];
    for (i = 0; i < uppers.length; i++) {
        string = string.replace(new RegExp('\\b' + uppers[i] + '\\b', 'g'), uppers[i].toUpperCase());
    }

    return string;
}
Ouatataz
  • 185
  • 3
  • 12
5

I think the simplest is using css.

function format_str(str) {
    str = str.toLowerCase();
    return '<span style="text-transform: capitalize">'+ str +'</span>';
}
wondim
  • 697
  • 15
  • 29
5

here's another solution using css (and javascript, if the text you want to transform is in uppercase):

html

<span id='text'>JOHN SMITH</span>

js

var str = document.getElementById('text').innerHtml;
var return_text = str.toLowerCase();

css

#text{text-transform:capitalize;}
henrie
  • 165
  • 1
  • 12
5

Here's a really simple & concise ES6 function to do this:

const titleCase = (str) => {
  return str.replace(/\w\S*/g, (t) => { return t.charAt(0).toUpperCase() + t.substr(1).toLowerCase() });
}

export default titleCase;

Works well included in a utilities folder and used as follows:

import titleCase from './utilities/titleCase.js';

const string = 'my title & string';

console.log(titleCase(string)); //-> 'My Title & String'
Hedley Smith
  • 1,307
  • 15
  • 12
5

jim-bob -> Jim-Bob

jim/bob -> Jim/Bob

jim_bob -> Jim_Bob

isn't -> Isn't

école -> École

McDonalds -> McDonalds

function toTitleCase(str) {
  return str.replace(/\p{L}+('\p{L}+)?/gu, function(txt) {
    return txt.charAt(0).toUpperCase() + txt.slice(1)
  })
}
o17t H1H' S'k
  • 2,541
  • 5
  • 31
  • 52
4

Taking the "lewax00" solution I created this simple solution that force to "w" starting with space or "w" that initiate de word, but is not able to remove the extra intermediate spaces.

"SOFÍA vergara".toLowerCase().replace(/\b(\s\w|^\w)/g, function (txt) { return txt.toUpperCase(); });

The result is "Sofía Vergara".

Asereware
  • 1,009
  • 6
  • 7
4

We have been having a discussion back here at the office and we think that trying to automatically correct the way people input names in the current way you want it doing is fraught with possible issues.

We have come up with several cases where different types of auto capitalization fall apart and these are just for English names alone, each language has its own complexities.

Issues with capitalizing the first letter of each name:

• Acronyms such as IBM aren’t allowed to be inputted, would turn into Ibm.

• The Name McDonald would turn into Mcdonald which is incorrect, the same thing is MacDonald too.

• Double barrelled names such as Marie-Tonks would get turned into Marie-tonks.

• Names like O’Connor would turn into O’connor.

For most of these you could write custom rules to deal with it, however, this still has issues with Acronyms as before and you get a new issue:

• Adding in a rule to fix names with Mac such as MacDonald, would the break names such as Macy turning it into MacY.

The only solution we have come up with that is never incorrect is to capitalize every letter which is a brute force method that the DBS appear to also use.

So if you want to automate the process it is as good as impossible to do without a dictionary of every single name and word and how it should be capitlized, If you don't have a rule that covers everything don't use it as it will just annoy your users and prompt people who want to enter their names correctly to go else where.

jjr2000
  • 547
  • 8
  • 20
  • You could test if the input string already seems to be properly cased, and only if it isnt (e.g. all lower or all upper) change the case with your best effort algorithm – dan-man Jul 12 '20 at 18:54
4

My one line solution:

String.prototype.capitalizeWords = function() {
    return this.split(" ").map(function(ele){ return ele[0].toUpperCase() + ele.slice(1).toLowerCase();}).join(" ");
};

Then, you can call the method capitalizeWords() on any string. For example:

var myS = "this actually works!";
myS.capitalizeWords();

>>> This Actually Works

My other solution:

function capitalizeFirstLetter(word) {
    return word[0].toUpperCase() + word.slice(1).toLowerCase();
}
String.prototype.capitalizeAllWords = function() {
    var arr = this.split(" ");
    for(var i = 0; i < arr.length; i++) {
        arr[i] = capitalizeFirstLetter(arr[i]);
    }
    return arr.join(" ");
};

Then, you can call the method capitalizeWords() on any string. For example:

var myStr = "this one works too!";
myStr.capitalizeWords();

>>> This One Works Too

Alternative solution based on Greg Dean answer:

function capitalizeFirstLetter(word) {
    return word[0].toUpperCase() + word.slice(1).toLowerCase();
}
String.prototype.capitalizeWords = function() {
    return this.replace(/\w\S*/g, capitalizeFirstLetter);
};

Then, you can call the method capitalizeWords() on any string. For example:

var myString = "yes and no";
myString.capitalizeWords()

>>> Yes And No
Fouad Boukredine
  • 1,495
  • 14
  • 18
4

Simple way to convert an individual word to title case

Using the "Slice" method and String concatenation

str.slice(0, 1).toUpperCase() + str.slice(1, str.length)

*Add .toLowerCase() to the end if you want to lowercase the rest of the word

Using ES6 Spread Operator, Map, and Join

[...str].map((w, i) => i === 0 ? w[0].toUpperCase() : w).join('')
mschwartz
  • 188
  • 2
  • 6
4

I've tested this solution for Turkish and it works with special characters too.

function toTitleCase(str) {
  return str.toLocaleLowerCase().replace(
    /(^|Ü|ü|Ş|ş|Ç|ç|İ|ı|Ö|ö|\w)\S*/g,
    (txt) => txt.charAt(0).toLocaleUpperCase() + txt.substring(1),
  )
}

console.log(toTitleCase('İSMAİL HAKKI'))
console.log(toTitleCase('ŞAHMARAN BİNBİR GECE MASALLARI'))
console.log(toTitleCase('TEKNOLOJİ ÜRÜNÜ'))

I've added "toLocaleLowerCase" at the begining since I've all caps data. You can discard it if you don't need it.

Using locale operations is important for non-english languages.

Kerem
  • 101
  • 2
  • 8
  • The selected answer is buggy. This is better. – Billy Jan 26 '22 at 21:33
  • `toTitleCase("TEKNOLOJİ ÜRÜNÜ")` is returning `Teknoloji̇ üRünü`. Fyi. – Ozgun Senyuva May 04 '22 at 08:19
  • @OzgunSenyuva thank you. I've edited my answer to fix the issue. – Kerem Jun 13 '22 at 13:24
  • "Using locale operations is important for non-english languages" - but your solution ignores locale operations. Your assumption that the character you need to act on is at char(0) is incorrect. For example, you need a test case that checks that the correct conversion of "oifig na bpasanna" is "Oifig na bPasanna" - "Oifig Na Bpasanna" isn't even close to correct. You also can't do toLocaleUpperCase on individual characters, ever; it just doesn't work. For example, OIFIG NA bPASANNA (note the 'b') is all upper case: https://commons.wikimedia.org/wiki/File:ALLCAPS_OIFIG_NA_bPASANNA.JPG – James Moore Aug 10 '22 at 20:56
  • Doesn’t work on ‘džungla’. – user3840170 Sep 02 '23 at 11:06
3

This is based on my solution for FreeCodeCamp's Bonfire "Title Case", which requires you to first convert the given string to all lower case and then convert every character proceeding a space to upper case.

Without using regex:

function titleCase(str) {
 return str.toLowerCase().split(' ').map(function(val) { return val.replace(val[0], val[0].toUpperCase()); }).join(' ');
}
3

A one-liner using regex, get all \g starting characters of words \b[a-zA-Z] , and apply .toUpperCase()

const textString = "Convert string to title case with Javascript.";
const converted = textString.replace(/\b[a-zA-Z]/g, (match) => match.toUpperCase());
console.log(converted)
its4zahoor
  • 1,709
  • 1
  • 16
  • 23
3

You can capitalize 1st char and join with the remaining string.

let str = 'john smith';
let res = str.split(" ");
res.forEach((w, index) => {
    res[index] =  w.charAt(0).toUpperCase().concat(w.slice(1, w.length))
});
res = res.join(" ");
console.log(res);
PaperinFlames
  • 642
  • 5
  • 6
3

var string = "tEsT"

string = string.toLowerCase() 
var output= string.charAt(0).toUpperCase() + string.slice(1)
console.log(output)
alert(output)
  
 var string = "tEsT"

 string = string.toLowerCase() 

 string.charAt(0).toUpperCase() + string.slice(1)
  • string.charAt(0) returns the character at the 0th index of the string.
  • toUpperCase() is a method that returns the uppercase equivalent of a string. It is applied to the first character of the string, returned by charAt(0).
  • string.slice(1) returns a new string that starts from the 1st index (the character at index 0 is excluded) till the end of the string.
  • Finally, the expression concatenates the result of toUpperCase() and string.slice(1) to create a new string with the first character capitalized.
Zahid
  • 54
  • 2
  • 4
  • Please explain the relevan difference of your proposal beyond what is given in https://stackoverflow.com/a/70546786/7733418 which seems where you just copied the core line of code from, without any explanation. – Yunnosch Feb 07 '23 at 20:52
  • @Yunnosch added explaination – Zahid Feb 07 '23 at 21:36
  • You explained the code. I'd like to know what the relevant difference is to the older, upvoted question, which seems to provide the same core solution. What is better here? If the code is not better, or not even different, what is the additional insight your post provided? You need to avoid the impression that you copied from an existing upvoted answer only to try and sneak some reputation off. Or that you simply did not bother to read existing answers first. – Yunnosch Feb 08 '23 at 06:57
  • 1
    Sorry @Yunnosch i haven't copied from outside and you can hit dislike if you disagree and the solution is not working in your side – Zahid Feb 16 '23 at 19:37
2

For those of us who are scared of regular expressions (lol):

function titleCase(str)
{
    var words = str.split(" ");
    for ( var i = 0; i < words.length; i++ )
    {
        var j = words[i].charAt(0).toUpperCase();
        words[i] = j + words[i].substr(1);
    }
    return words.join(" ");
}
lashja
  • 493
  • 10
  • 21
2

https://lodash.com/docs/4.17.11#capitalize

Use Lodash Library..!! More Reliable

_.capitalize('FRED'); => 'Fred'
Siddharth
  • 369
  • 3
  • 7
2

My list is based on three quick searches. One for a list of words not to be capitalized, and one for a full list of prepositions.

One final search made the suggestion that prepositions 5 letters or longer should be capitalized, which is something I liked. My purpose is for informal use. I left 'without' in their, because it's the obvious counterpart to with.

So it capitalizes acronyms, the first letter of the title, and the first letter of most words.

It is not intended to handle words in caps-lock. I wanted to leave those alone.

function camelCase(str) {
  return str.replace(/((?:^|\.)\w|\b(?!(?:a|amid|an|and|anti|as|at|but|but|by|by|down|for|for|for|from|from|in|into|like|near|nor|of|of|off|on|on|onto|or|over|past|per|plus|save|so|than|the|to|to|up|upon|via|with|without|yet)\b)\w)/g, function(character) {
  return character.toUpperCase();
})}
    
console.log(camelCase('The quick brown fox jumped over the lazy dog, named butter, who was taking a nap outside the u.s. Post Office. The fox jumped so high that NASA saw him on their radar.'));
Regular Jo
  • 5,190
  • 3
  • 25
  • 47
  • What if I want to create a `toTitleCase()` method, suitable to use just like the "native" `toLowerCase()`: `str.toTitleCase()`, how would you do that? – Razvan Zamfir Sep 17 '20 at 15:14
  • @RazvanZamfir You can modify the String `prototype`. You can do `String.prototype.toTitleCase = function() {...}` https://www.codementor.io/@dhruvkumarjha/extending-the-javascript-string-prototype-f3o5xjia6 – Regular Jo Sep 17 '20 at 21:03
2

Here is my answer Guys Please comment and like if your problem solved.

function toTitleCase(str) {
  return str.replace(
    /(\w*\W*|\w*)\s*/g,
    function(txt) {
    return(txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase())
    }
  ); 
}
<form>
  Input:
  <br /><textarea name="input" onchange="form.output.value=toTitleCase(this.value)" onkeyup="form.output.value=toTitleCase(this.value)"></textarea>
  <br />Output:
  <br /><textarea name="output" readonly onclick="select(this)"></textarea>
</form>
Soham Patel
  • 125
  • 5
2

I highly recommend just using an open source NPM package if you can, this package works great in typescript:

NPM: https://www.npmjs.com/package/title-case

Github: https://github.com/blakeembrey/change-case/tree/master/packages/title-case#readme

Run npm install title-case to add the package to your project.

Example Code using the title-case npm package:

import { titleCase } from "title-case";

titleCase("string"); //=> "String"
titleCase("follow step-by-step instructions"); //=> "Follow Step-by-Step Instructions"
Brendan Sluke
  • 857
  • 10
  • 11
1

It's not short but here is what I came up with on a recent assignment in school:

var myPoem = 'What is a jQuery but a misunderstood object?'
//What is a jQuery but a misunderstood object? --> What Is A JQuery But A Misunderstood Object?

  //code here
var capitalize = function(str) {
  var strArr = str.split(' ');
  var newArr = [];
  for (var i = 0; i < strArr.length; i++) {
    newArr.push(strArr[i].charAt(0).toUpperCase() + strArr[i].slice(1))
  };
  return newArr.join(' ')  
}

var fixedPoem = capitalize(myPoem);
alert(fixedPoem);
1

Prototype solution of Greg Dean's solution:

String.prototype.capitalize = function() {
  return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}
dipole_moment
  • 5,266
  • 4
  • 39
  • 55
1

Simpler more performant version, with simple caching.

  var TITLE_CASE_LOWER_MAP = {
    'a': 1, 'an': 1, 'and': 1, 'as': 1, 'at': 1, 'but': 1, 'by': 1, 'en':1, 'with': 1,
    'for': 1, 'if': 1, 'in': 1, 'of': 1, 'on': 1, 'the': 1, 'to': 1, 'via': 1
  };

  // LEAK/CACHE TODO: evaluate using LRU.
  var TITLE_CASE_CACHE = new Object();

  toTitleCase: function (title) {
    if (!title) return null;

    var result = TITLE_CASE_CACHE[title];
    if (result) {
      return result;
    }

    result = "";
    var split = title.toLowerCase().split(" ");
    for (var i=0; i < split.length; i++) {

      if (i > 0) {
        result += " ";
      }

      var word = split[i];
      if (i == 0 || TITLE_CASE_LOWER_MAP[word] != 1) {
        word = word.substr(0,1).toUpperCase() + word.substr(1);
      }

      result += word;
    }

    TITLE_CASE_CACHE[title] = result;

    return result;
  },
Rafael Sanches
  • 1,823
  • 21
  • 28
1

My simple and easy version to the problem:

    function titlecase(str){
    var arr=[];  
    var str1=str.split(' ');
    for (var i = 0; i < str1.length; i++) {
    var upper= str1[i].charAt(0).toUpperCase()+ str1[i].substr(1);
    arr.push(upper);
     };
      return arr.join(' ');
    }
    titlecase('my name is suryatapa roy');
Suryatapa
  • 39
  • 3
1

Here is a compact solution to the problem:

function Title_Case(phrase) 
{
  var revised = phrase.charAt(0).toUpperCase();

  for ( var i = 1; i < phrase.length; i++ ) {

    if (phrase.charAt(i - 1) == " ") {
     revised += phrase.charAt(i).toUpperCase(); }
    else {
     revised += phrase.charAt(i).toLowerCase(); }

   }

return revised;
}
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
Covfefe
  • 11
  • 1
1

There's been some great answers, but, with many people using regex to find the word, but, for some reason, nobody else uses regex to replace the first character. For explanation, I'll provide a long solution and a shorter one.

The long solution (more explanatory). By using regular expression [^\s_\-/]* we can find every word in the sentence. Subsequently, we can use the regular expression . to match to the first character in a word. Using the regular expression version of replace for both of these, we can change the solution like this:

function toUpperCase(str) { return str.toUpperCase(); }
function capitalizeWord(word) { return word.replace(/./, toUpperCase); }
function capitalize(sentence) { return sentence.toLowerCase().replace(/[^\s_\-/]*/g, capitalizeWord); }

console.log(capitalize("hello world")); // Outputs: Hello World

For a single function that does the same thing, we nest the replace calls as follows:

function capitalize(sentence) {
  return sentence.toLowerCase().replace(/[^\s_\-/]*/g, function (word) {
    return word.replace(/./, function (ch) { return ch.toUpperCase(); } );
  } );
}

console.log(capitalize("hello world")); // Outputs: Hello World
Stephen Quan
  • 21,481
  • 4
  • 88
  • 75
1

this is a test ---> This Is A Test

function capitalize(str) {

  const word = [];

  for (let char of str.split(' ')) {
    word.push(char[0].toUpperCase() + char.slice(1))
  }

  return word.join(' ');

}

console.log(capitalize("this is a test"));
bajran
  • 1,433
  • 14
  • 23
1

john smith -> John Smith

'john smith'.replace(/(^\w|\s+\w){1}/g, function(str){ return str.toUpperCase() } );
1

A solution using lodash -

import { words, lowerCase, capitalize, endsWith, padEnd } from 'lodash';
const titleCase = string =>
  padEnd(
    words(string, /[^ ]+/g)
      .map(lowerCase)
      .map(capitalize)
      .join(' '),
    string.length,
  );
Avinash
  • 779
  • 7
  • 18
  • why not `_.startCase('john smith');`? https://lodash.com/docs/4.17.15#startCase – w3debugger Feb 06 '20 at 21:59
  • _.startCase removes any special characters that are present in your string. `_.startCase('john-smith') => John Smith`. Also, if the whole string is uppercase & if you want to have just the first characters as Caps, startCase doesn't help. `_.startCase('JOHN SMITH') => JOHN SMITH` – Avinash Feb 10 '20 at 18:24
  • aaah, didn't know about capital letters. but in that case, we can use `_.startCase('HELLO'.toLowerCase())` ? – w3debugger Feb 12 '20 at 08:04
0

As full featured as John Resig's solution, but as a one-liner: (based on this github project)

function toTitleCase(e){var t=/^(a|an|and|as|at|but|by|en|for|if|in|of|on|or|the|to|vs?\.?|via)$/i;return e.replace(/([^\W_]+[^\s-]*) */g,function(e,n,r,i){return r>0&&r+n.length!==i.length&&n.search(t)>-1&&i.charAt(r-2)!==":"&&i.charAt(r-1).search(/[^\s-]/)<0?e.toLowerCase():n.substr(1).search(/[A-Z]|\../)>-1?e:e.charAt(0).toUpperCase()+e.substr(1)})};

console.log( toTitleCase( "ignores mixed case words like iTunes, and allows AT&A and website.com/address etc..." ) );
Billy Moon
  • 57,113
  • 24
  • 136
  • 237
0
function toTitleCase(str) {
  var strnew = "";
  var i = 0;

  for (i = 0; i < str.length; i++) {
    if (i == 0) {
      strnew = strnew + str[i].toUpperCase();
    } else if (i != 0 && str[i - 1] == " ") {
      strnew = strnew + str[i].toUpperCase();
    } else {
      strnew = strnew + str[i];
    }
  }

  alert(strnew);
}

toTitleCase("hello world how are u");
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
vijayscode
  • 1,905
  • 4
  • 21
  • 37
0

This is one line solution, if you want convert every work in the string, Split the string by " ", iterate over the parts and apply this solution to each part, add every converted part to a array and join it with " ".

var stringToConvert = 'john';
stringToConvert = stringToConvert.charAt(0).toUpperCase() + Array.prototype.slice.call(stringToConvert, 1).join('');
console.log(stringToConvert);
aagamezl
  • 49
  • 3
0
function titleCase(str) {
    str = str.toLowerCase();

    var strArray = str.split(" ");


    for(var i = 0; i < strArray.length; i++){
        strArray[i] = strArray[i].charAt(0).toUpperCase() + strArray[i].substr(1);

    }

    var result = strArray.join(" ");

    //Return the string
    return result;
}
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
0
String.prototype.capitalize = function() {
    return this.toLowerCase().split(' ').map(capFirst).join(' ');
    function capFirst(str) {
        return str.length === 0 ? str : str[0].toUpperCase() + str.substr(1);
    }
}

Usage:

"hello world".capitalize()
zurfyx
  • 31,043
  • 20
  • 111
  • 145
0

Just another version to add to the mix. This will also check if the string.length is 0:

String.prototype.toTitleCase = function() {
    var str = this;
    if(!str.length) {
        return "";
    }
    str = str.split(" ");
    for(var i = 0; i < str.length; i++) {
        str[i] = str[i].charAt(0).toUpperCase() + (str[i].substr(1).length ? str[i].substr(1) : '');
    }
    return (str.length ? str.join(" ") : str);
};
Scott
  • 772
  • 1
  • 11
  • 20
0

Robust Functional programming way to do Title Case Function

Exaplin Version

function toTitleCase(input){
    let output = input
        .split(' ')  // 'HOw aRe YOU' => ['HOw' 'aRe' 'YOU']
        .map((letter) => {
            let firstLetter = letter[0].toUpperCase() // H , a , Y  => H , A , Y
            let restLetters = letter.substring(1).toLowerCase() // Ow, Re, OU => ow, re, ou
            return firstLetter + restLetters // conbine together
        })
        .join(' ') //['How' 'Are' 'You'] => 'How Are You'
    return output
}

Implementation version

function toTitleCase(input){
    return input
            .split(' ')
            .map(i => i[0].toUpperCase() + i.substring(1).toLowerCase())
            .join(' ') 
}

toTitleCase('HoW ARe yoU') // reuturn 'How Are You'
Wayne Chiu
  • 5,830
  • 2
  • 22
  • 19
0

This solution takes punctuation into account for new sentences, handles quotations, converts minor words to lowercase and ignores acronyms or all-caps words.

var stopWordsArray = new Array("a", "all", "am", "an", "and", "any", "are", "as", "at", "be", "but", "by", "can", "can't", "did", "didn't", "do", "does", "doesn't", "don't", "else", "for", "get", "gets", "go", "got", "had", "has", "he", "he's", "her", "here", "hers", "hi", "him", "his", "how", "i'd", "i'll", "i'm", "i've", "if", "in", "is", "isn't", "it", "it's", "its", "let", "let's", "may", "me", "my", "no", "of", "off", "on", "our", "ours", "she", "so", "than", "that", "that's", "thats", "the", "their", "theirs", "them", "then", "there", "there's", "these", "they", "they'd", "they'll", "they're", "they've", "this", "those", "to", "too", "try", "until", "us", "want", "wants", "was", "wasn't", "we", "we'd", "we'll", "we're", "we've", "well", "went", "were", "weren't", "what", "what's", "when", "where", "which", "who", "who's", "whose", "why", "will", "with", "won't", "would", "yes", "yet", "you", "you'd", "you'll", "you're", "you've", "your");

// Only significant words are transformed. Handles acronyms and punctuation
String.prototype.toTitleCase = function() {
    var newSentence = true;
    return this.split(/\s+/).map(function(word) {
        if (word == "") { return; }
        var canCapitalise = true;
        // Get the pos of the first alpha char (word might start with " or ')
        var firstAlphaCharPos = word.search(/\w/);
        // Check for uppercase char that is not the first char (might be acronym or all caps)
        if (word.search(/[A-Z]/) > 0) {
            canCapitalise = false;
        } else if (stopWordsArray.indexOf(word) != -1) {
            // Is a stop word and not a new sentence
            word.toLowerCase();
            if (!newSentence) {
                canCapitalise = false;
            }
        }
        // Is this the last word in a sentence?
        newSentence = (word.search(/[\.!\?:]['"]?$/) > 0)? true : false;
        return (canCapitalise)? word.replace(word[firstAlphaCharPos], word[firstAlphaCharPos].toUpperCase()) : word;
    }).join(' ');
}

// Pass a string using dot notation:
alert("A critical examination of Plato's view of the human nature".toTitleCase());
var str = "Ten years on: a study into the effectiveness of NCEA in New Zealand schools";
str.toTitleCase());
str = "\"Where to from here?\" the effectivness of eLearning in childhood education";
alert(str.toTitleCase());

/* Result:
A Critical Examination of Plato's View of the Human Nature.
Ten Years On: A Study Into the Effectiveness of NCEA in New Zealand Schools.
"Where to From Here?" The Effectivness of eLearning in Childhood Education. */
chasnz
  • 179
  • 1
  • 6
0

Converting a text to titlecase consists in converting the initial of each word to uppercase and the remaining characters to lowercase. Initials are defined as word characters not preceded by word characters; they can be matched by a negative lookbehind assertion.

  • Implementation for word characters defined as non whitespaces (i.e. not \s, that is \S):
function toTitleCase(text) {
  return text.toLowerCase().replace(
    /(?<!\S)\S/ug, match => match.toUpperCase()
  );
}


toTitleCase('don’t perform input–output ’til out-of-memory');
// 'Don’t Perform Input–output ’til Out-of-memory'
  • Implementation for word characters defined as non whitespaces and non dash punctuation marks (i.e. not \s and not \p{Pd}, that is [^\s\p{Pd}]):
function toTitleCase(text) {
  return text.toLowerCase().replace(
    /(?<![^\s\p{Pd}])[^\s\p{Pd}]/ug, match => match.toUpperCase()
  );
}


toTitleCase('don’t perform input–output ’til out-of-memory');
// 'Don’t Perform Input–Output ’til Out-Of-Memory'
Géry Ogam
  • 6,336
  • 4
  • 38
  • 67
-1

A method use reduce

function titleCase(str) {
  const arr = str.split(" ");
  const result = arr.reduce((acc, cur) => {
    const newStr = cur[0].toUpperCase() + cur.slice(1).toLowerCase();
    return acc += `${newStr} `
  },"")
  return result.slice(0, result.length-1);
}
Wayne Li
  • 411
  • 1
  • 6
  • 16
-1

Another approach to achieve something similar can be as follows.

formatName(name) {
    let nam = '';
    name.split(' ').map((word, index) => {
        if (index === 0) {
            nam += word.split('').map((l, i) => i === 0 ? l.toUpperCase() : l.toLowerCase()).join('');
        } else {
            nam += ' ' + word.split('').map(l => l.toLowerCase()).join('');
        }
    });
    return nam;
}
usmany
  • 146
  • 2
  • 11
-1
ES-6 way to get title case of a word or entire line.
ex. input = 'hEllo' --> result = 'Hello'
ex. input = 'heLLo woRLd' --> result = 'Hello World'

const getTitleCase = (str) => {
  if(str.toLowerCase().indexOf(' ') > 0) {
    return str.toLowerCase().split(' ').map((word) => {
      return word.replace(word[0], word[0].toUpperCase());
    }).join(' ');
  }
  else {
    return str.slice(0, 1).toUpperCase() + str.slice(1).toLowerCase();
  }
}
Mayur Nandane
  • 309
  • 2
  • 8
-1

I think you should try with this function.

var toTitleCase = function (str) {
    str = str.toLowerCase().split(' ');
    for (var i = 0; i < str.length; i++) {
        str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1);
    }
    return str.join(' ');
};
Neeraj Kumar
  • 6,045
  • 2
  • 31
  • 23
  • What if I want to create a `toTitleCase()` method, suitable to use just like the "native" `toLowerCase()`: `str.toTitleCase()`? – Razvan Zamfir Sep 17 '20 at 15:14
-1

My answer using regex.

for more details regex: https://regex101.com/r/AgRM3p/1

function toTitleCase(string = '') {
  const regex = /^[a-z]{0,1}|\s\w/gi;

  string = string.toLowerCase();

  string.match(regex).forEach((char) => {
    string = string.replace(char, char.toUpperCase());
  });

  return string;
}

const input = document.getElementById('fullname');
const button = document.getElementById('button');
const result = document.getElementById('result');

button.addEventListener('click', () => {
  result.innerText = toTitleCase(input.value);
});
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test</title>
</head>
<body>
    <input type="text" id="fullname">
    <button id="button">click me</button>
    <p id="result">Result here</p>
    <script src="./index.js"></script>
</body>
</html>
Max
  • 393
  • 4
  • 4
-1

No regex, no loop, no split, no substring:

String.prototype.toTitleCase = function () { return this.valueOf().toLowerCase().replace(this.valueOf()[0], this.valueOf()[0].toUpperCase()); }

console.log('laiLA'.toTitleCase());
Anshul
  • 117
  • 1
  • 2
-1

If you'd like to use an NPM library, check out title-case:

Installation:

npm install title-case --save

Usage:

import { titleCase } from "title-case";

titleCase("string"); //=> "String"
titleCase("follow step-by-step instructions"); //=> "Follow Step-by-Step Instructions"
rinogo
  • 8,491
  • 12
  • 61
  • 102
  • why use a library for such a simple thing? – Aaron Nov 08 '22 at 11:31
  • @Aaron Depending on what you're trying to do, it *could* be a simple thing, but for me it wasn't. "Title case" is ambiguous - I needed [proper English title case](https://en.wikipedia.org/wiki/Letter_case#Title_case), which is [exactly what this neat library does](https://github.com/blakeembrey/change-case/blob/master/packages/title-case/src/index.ts). – rinogo Nov 08 '22 at 19:14
-2

ES6 one liner

const toTitleCase = string => string.split(' ').map((word) => [word[0].toUpperCase(), ...word.substr(1)].join('')).join(' ');
hacklikecrack
  • 1,360
  • 1
  • 16
  • 20