0

Let me preface my question by saying that I'm a beginning software engineering student in an Intro to JavaScript course. I'm having an issue with an assignment for the JavaScript course.

Here is the assignment, "Create a file called nameSplit.html that uses one single prompt() call to get a full name from the user--first, middle and last name. Then, split the input into an array and use a loop to output each name on a separate line. For full credit, you must use a loop rather than joining the array back into a string."

My issue is that when I write the split string to the page, it writes the split string multiple times on separate lines which isn't what I want. What I want is for the string to separate and each part to be on a separate line.

Here's my code.

var fullName = prompt("Please enter your full name: first, middle (if you have one), and last name.", "Full Middle Last");

function nameSplit(name) {
  var nameAfterSplit = name.split(" ");

  for (i = 0; i < nameAfterSplit.length; i++) {
    document.write(nameAfterSplit + "<br />");
  }
}
nameSplit(fullName);

Can anyone help me with this?

Ele
  • 33,468
  • 7
  • 37
  • 75

3 Answers3

1

String.split generates an array and you're printing the whole array inside the loop. You must use the index [i] to select a specific array element. Change to: document.write(nameAfterSplit[i] + "<br />");

Leandro Luque
  • 518
  • 3
  • 6
1

You should output the i-th element of the array containing the split parts: use nameAfterSplit[i] instead of nameAfterSplit

Hero Wanders
  • 3,237
  • 1
  • 10
  • 14
1

Look closely at what you're printing. While you do split() your string correctly, when you print it you're printing not just each segment but the whole split-string. As split returns an array, what you need to do is target each individual element on each loop iteration.

var fullName = prompt("Please enter your full name: first, middle (if you have one), and last name.", "Full Middle Last");
  
  function nameSplit(name){
   var nameAfterSplit = name.split(" ");
  
   for(i = 0; i < nameAfterSplit.length; i++){
   document.write(nameAfterSplit[i] + "<br />");
   }
  }
  nameSplit(fullName);
Frish
  • 1,371
  • 10
  • 20