admin管理员组

文章数量:1430061

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"

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"

Share Improve this question asked Sep 15, 2021 at 14:46 Blackwell805Blackwell805 511 silver badge8 bronze badges 4
  • 2 Have a look at string.split() and string.substr(). – gen_Eric Commented Sep 15, 2021 at 14:49
  • 1 please make an attempt before asking – depperm Commented Sep 15, 2021 at 14:50
  • This question does not contain enough research and is very vague. If you would at least try to research a little bit on what you are trying to do, I am certain that you will see some results. – Joe Commented Sep 15, 2021 at 14:50
  • Thank you for the feedback! – Blackwell805 Commented Sep 15, 2021 at 20:48
Add a ment  | 

2 Answers 2

Reset to default 5

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);

If you wanted to support multiple initials you could do something like:

let name = "Mike Fred Jones"

//string.split() name by [space].

var names = name.split(" ")

//Temporary variable for initialled name.

var newname = ""

//For each name in the names array.
for (n in names){

    //make sure its not the last.
    
    if (String(names[n]).valueOf() != String(names[names.length-1]).valueOf()){
        
        //Append the first letter of the name and [.]
        
        newname = newname + names[n][0] + "." 
        
    }
}

//Append initials, [space], and last name.

newname = newname + " " + names[names.length-1]

console.log(newname) //Outputs M.F. Jones

本文标签: javascriptDisplay First Initial of First name and full Last nameStack Overflow