Web Dev 101 - Fundamentals 3

Hi guys,

I’ve just completed the Practice task on Fundamentals 3. It did take me a a few hours to complete the task as best as I could (with some googling off-course lol). I was wondering however though, on this question:

Write a function called capitalize that takes a string and returns that string with only the first letter capitalized.
Make sure that it can take strings that are lowercase, UPPERCASE or BoTh.

I wrote the code below, and it is functioning. It brings up the output “He”. However, I am just wondering how I can write it efficiently enough to bring up the whole sentence of “Hello from mars!” instead of just he “He”.

str = "hElLo fROm Mars!" function capitalize(str) { return str.toUpperCase()[0] + str.toLowerCase()[1]; } console.log(capitalize(str))

1 Like

Hello @lisaxo

I hope my answer helps you.
My answer is below with comments.

"use strict";

function firstLetterToUpper(strIn = "")
{
  // get first character and convert to lower case
  const firstCharUpperCase = strIn[0].toUpperCase();

  // convert all characters to lower case
  // and then get the characters from 2nd character upto the end 
  const tmpStr = strIn.toLowerCase().slice(1, strIn.length);

  // concatenate the string
  const str = firstCharUpperCase + tmpStr;

  console.log(str);
  return str;
}

firstLetterToUpper("hElLo fROm Mars!");

Henry

1 Like

Thank you. I’ll give it a try.

Hey @lisaxo

The issue with your particular code is that you are only returning the first (str.toUpperCase()[0]) and second letters (str.toLowerCase()[1]).

Look up the String.prototype.slice() method. It will be helpful in your case.

@henry i read through your solution and i had the best ‘aha’ moment. Thank you so much!

2 Likes

Hey all,

I was having some trouble with this one but found out that this works just fine after playing with it a bit:

function capitalize() {

let mystring = prompt(“Enter a word.”)
return mystring.charAt(0).toUpperCase() + mystring.toLowerCase().slice(1);

}

console.log(capitalize())

mystring.charAt(0).toUpperCase() will take the first letter and always capitalize it

mystring.toLowerCase().slice(1) will lowercase everything starting at the second letter.

1 Like

Clean work :slight_smile:
Cheers

Hey Brutus! What can I do so, instead of getting the result in the console, I can just see the result in the main page?
Thanks for the help!

I came up with this one

function capitalize() {
let str = prompt(“Write something”)
return str.charAt(0).toUpperCase() + str.toLowerCase().slice(1) || “you have not written anything”
}

document.write(capitalize());