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
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 calledstr
, passed into the function –capital_letter(str)
So in a console you could do this:
Which returns:
and:
Which returns:
finally:
Which returns:
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