skip to Main Content

I’m new to JS.
I’ve written a program that capitalizes the first letter of each word in a given string. I also found another piece of code on w3resource.com that does the same, but I don’t quite understand how it works.
Here’s my code:

function capFirstLetters(str) {
  const words = str.split(" ");
  for (let i = 0; i < words.length; i++) {
    const letters = words[i].split("");
    letters[0] = letters[0].toUpperCase();
    words[i] = letters.join("");
  }
  return words.join(" ");
}

console.log(capFirstLetters("i wrote a program that capitalizes the first letter of each word in a string."));

Here’s the code from w3resource.com:

function capital_letter(str) {
  str = str.split(" ");
  for (var i = 0, x = str.length; i < x; i++) {
    str[i] = str[i][0].toUpperCase() + str[i].substr(1);
  }
  return str.join(" ");
}
console.log(capital_letter("i wrote a program that capitalizes the first letter of each word in a string."));

What I don’t understand is the line of code inside the for loop. Can you work with the letters of a string as elements of an array without first creating an array from the string?

2

Answers


  1. The split function, as described in w3school documentation, creates an array from a string. The following line creates an array variable called str, from the string variable called str, passed into the function – capital_letter(str)

    str = str.split(" ");
    

    So in a console you could do this:

    str="i am a string";
    

    Which returns:

    'i am a string'
    

    and:

    str = str.split(" ");
    

    Which returns:

    (4) ['i', 'am', 'a', 'string']
    

    finally:

    str[3];
    

    Which returns:

    'string'
    
    Login or Signup to reply.
  2. See the other answers for the explanation of the split.

    I answer your other question: Yes you can access the string as an array of letters.

    However since a string is immutable (cannot be changed in place) we need to copy it anyway. Here I use […spread] to make the array but I index the string directly

    const capFirstLetters = str => [...str]
      .map((letter,i) => (i===0 || ".?! ".includes(str[i-1])) ? letter.toUpperCase() : letter)
      .join("");
    
    console.log(capFirstLetters("i wrote a program that capitalizes the first letter of each word in a string."));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search