I have a string containing a person's first and last name such as
You can do this by splitting the name apart by space and modifying the last name.
var name = "John Doe"; // store the name var nameParts = name.split(" "); // split the name by spaces var lastName = nameParts[nameParts.length - 1]; // get the last name lastName = lastName.substring(0, 1) + "."; // replace the last name with the first letter and a full stop nameParts[nameParts.length - 1] = lastName; // insert the last name back into the array of names at the end name = nameParts.join(" "); // join the names back together with their original spaces console.log(name); // gives "John D."
This also satisfies the name
John Frank Doe as discussed in your question's comments, and will give
John Frank D. in that case.