mardi 30 juin 2020

Is there a way to slice a string in a new variable using JavaScript? [closed]

I am using JavaScript for a pop up that when the user visits the web page there is a chart saying What is your name? So the user need to write his name. In just one field. If the user writes two words the program would dive the name into separate first and last name strings.

I'm using this code but is not working the slice method for the last name, it just give in the first name everything. What I am doing wrong?

var fullname;
fullname = prompt("What is your name?");
fullname.indexOf(" ");

var indexOfSpace = fullname.indexOf(" ");
var firstname = "";
var lastname = "";

if (fullname.indexOf = -1) {
  firstname = fullname;
  lastname = "";
} else {
  firstname = fullname;
  lastname = fullname.slice(fullname.indexOf + 1);
}


console.log("Your visitor wrote : " + fullname + "\n\n" +
  "So his first name is: " + firstname + "\n" +
  " and" + "\n" +
  "his lastname is: " + lastname
);
alert("You wrote : " + fullname + "\n\n" +
  "So your first name is: " + firstname + "\n" +
  " and" + "\n" +
  "your lastname is: " + lastname + "!"
);

Aucun commentaire:

Enregistrer un commentaire