Javascript program get initials from a name

Synchlab Coding
0
function getInitials (name) {
   return name.split(” ”).map((char) ⇒ {
   return char[0];
  }).join(” ”)
}
console.log(getInitials(”John F Kennedy”));

1)  name.split(" "): This part of the code splits the input name into an array of words using the space character as a delimiter.

2).map((char) => { return char[0]; }): The map function is used to iterate over each element of the array (each word) and applies the provided function to transform each element. In this case, it takes each word and extracts the first character (initial) using char[0]. The result is an array of initials.

3)..join(" "): Finally, the join method is used to concatenate the elements of the array into a single string, separated by a space. This creates a string of initials separated by spaces.

So, when we call getInitials("John F Kennedy"), it would return the string "J F K", representing the initials of the given name. 




Post a Comment

0Comments

Post a Comment (0)