-1
var string = "deceMber iS Here" 

I tried this but I get an error saying it is not a function.

string.split(" ").toUpperCase()

I want output this way "December, Is, Here"

edit: This question is not a duplicate. I did lot of search and the links that provided did not meet my need. It is very specific question.

Ann
  • 139
  • 7
  • 1
    That question has already been answered. http://stackoverflow.com/questions/1026069/capitalize-the-first-letter-of-string-in-javascript – Sehab Dec 01 '15 at 19:02
  • var array = string.toLowerCase().split(" "); for(var i = 0; i < array.length; i++){ array[i][0] = array[i][0].toUpperCase(); }. I don't know If char type has the function toUpperCase(); – NPToita Dec 01 '15 at 19:10
  • @Ann Please explain why you this isn't a duplicate. What you're asking for is definitely title case. The answers in the linked question assume the original string is lower-cased. So, lower-case your string and then use one of the solutions in the linked question. Voting to leave this closed. – Rob Dec 03 '15 at 02:40
  • Rob, this question deals with three things- converting to lowercase, title-casing and mainly having commas in the string like `"December, Is, Here"` – Ann Dec 03 '15 at 02:52

3 Answers3

0

When you call string.split(" "), the result is an array of the substrings split by spaces. toUppercase() must be called on a string, not an array. This is why you are getting an error stating toUppercase() is not a function.

To capitalize the first letter in each of the split substrings, I'd see Sehab's recommendation: How do I make the first letter of a string uppercase in JavaScript?

Community
  • 1
  • 1
0

With string.split(" ").toUpperCase(), what you're doing is splitting a string into an array (['deceMber'],['iS'],['Here']) and trying to toUpperCase() it. Array's don't have this method, hence the error message.

You need to loop through each element in this array, set it to lower case, and then capitalize the first letter. After this, you can join them together with a ", ".

var string = "deceMber iS Here" 
var arr = string.split(" ");

for(var i = 0; i < arr.length; i++){
    arr[i] = arr[i].toLowerCase();
    arr[i] = arr[i].charAt(0).toUpperCase() + arr[i].slice(1);
}

str = arr.join(', ');
neilsimp1
  • 1,242
  • 1
  • 11
  • 25
0

First make the string lowercase, then replace first letter of each word with the uppercase.

var string = "deceMber iS Here";

console.log(string.toLowerCase().replace(/(^|\s)([a-z])/g, function(m,p1,p2){ return p1+p2.toUpperCase(); }));
depperm
  • 10,606
  • 4
  • 43
  • 67