Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Capitalize items in grocery list

How Can i capitalise items in the grocery list, there's a method for converting to lower case (toLowerCase()) and upper case (toUpperCase). What's there for capitalising ? e.g var items = [ 'belt', 'milk', 'egg' ]; --> items = ['Belt', 'Milk', 'Egg'];

2 Answers

var items = [ 'belt', 'milk', 'egg' ]; 
for (i=0; i < items.length; i++){

  var beginLetter = (items[i].substring(0,1));
  var remainLetter = (items[i].substring(1,items.length+1));

  document.write(beginLetter.toUpperCase() + remainLetter + "<br>");
}

Thanks Antonio,

Steven Parker
Steven Parker
243,656 Points

That's usually known as "title case", and some languages provide a built-in function for it but JavaScript does not.

But it's easy enough to add one, here's one way:

String.prototype.toTitleCase = function () {
  return this.toLowerCase().split(' ').map(w => w[0].toUpperCase() + w.slice(1)).join(' ');
}

console.log("new tiTLe case stRIng functION".toTitleCase())  // "New Title Case String Function"

var items = [ 'belt', 'milk', 'egg' ];
items = items.map(i => i.toTitleCase());
console.log(items);                                          // ["Belt", "Milk", "Egg"]

Thanks Steven, pls can you explain how the .map() function works, it seems a bit complex....

Steven Parker
Steven Parker
243,656 Points

It's covered in this course, along with some other really useful techniques: JavaScript Array Iteration Methods.