Display First Initial of First name and full Last name

In Javascript, I want to show in a history of events the first initial of the first name and the full last name.

Example:

let name = "Mike Jones"

Desired result —> “M. Jones”

Answer

You should utilize string.split() to split up the parts of the name, then use string.substr() to get the first initial, then use array.join() to glue the parts back together.

let name = "Mike Jones" // Who? Mike Jones

// Create an array containing each of the words in the name
var names = name.split(/s+/);

// Replaces the first name with an initial, followed by a period.
names[0] = names[0].substr(0, 1) + ".";

// Glue the pieces back together.
var name_abbr = names.join(' ');

console.log(name_abbr);

Or if you want to get fancy, you could use some regex to get the first letter of the first word, and then everything else, and then just put a period between them.

let name = "Mike Jones" // Who? Mike Jones

var parts = name.match(/^([a-zA-Z])[^s]*(.*)$/);
var abbr_name = parts[1] + "." + parts[2];

console.log(abbr_name);