Stavros_S Stavros_S - 4 months ago 6x
Javascript Question

How to use substring() when the string has a space in it

I have a string containing a person's first and last name such as

John Doe
. I would like to convert this string to
John D.
Normally, I would just use
on the last name variable, but how can I achieve this when the first and last name are one string with a space in between?


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.