Web Dev 101 - Fundamentals 3


#1

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))


#2

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


#3

Thank you. I’ll give it a try.


#4

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.