0

I am trying to build a JavaScript initcap function which correctly converts the first letter in each word to upper case as the other letters to lower case.

All examples I have found converts the first character which is incorrect, eg: joe smith (c e o) should convert to Joe Smith (C E O), not to Joe Smith (c E O)

CSS transform is not an option as the value is returned to a server.

Probably using regular expressions is the way to go but I am no expert at these. Any help ?

  • I bet the scripts are working fine. If I had to guess, their converting the first ***character*** not necessarily the first letter. (i.e. in your example above, the script is probably trying to convert the `(` rather than the `c`). Add a check to ensure the first character is a character from `A-Z` and then uppercase it. – War10ck May 19 '14 at 15:23

2 Answers2

0

Small edit on the answer that this duplicates, if you read the comments to the accepted answer you will find your answer there:

function toTitleCase(str)
{
    return str.replace(/([^\W_]+[^\s-]*) */g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}
fmsf
  • 36,317
  • 49
  • 147
  • 195
0

Another version based ok lookahead:

joe smith(c e o)'.replace(/\b[a-z](?=(?:[a-z]|\W|$))/g, function($0) {
    return $0.toUpperCase();})
//=> "Joe Smith(C E O)"
anubhava
  • 761,203
  • 64
  • 569
  • 643