Split First name and Last name using javascript

后端 未结 20 3027
悲&欢浪女
悲&欢浪女 2020-12-08 06:39

I have a user with a name Paul Steve Panakkal. It\'s a long name it won\'t fit to the div container. So is there anyway to split first name and lastname fro

相关标签:
20条回答
  • 2020-12-08 07:08

    Watch out for edge-cases like only a first name being provided or two or more spaces being entered. If you only want to parse out the first and last name, this will do the trick (full name should always contain at least 1 character to avoid first_name being set to an empty string):

    var full_name_split = "Paul Steve Panakkal".split(" ");
    var first_name = full_name_split[0];
    var last_name = full_name_split.length > 1 ? full_name_split[full_name_split.length - 1] : null;
    
    0 讨论(0)
  • 2020-12-08 07:08
    var fullName = "Paul Steve Panakkal";
    

    You can use the split function to split the full name then the result like displaying elements in an array or list.

    This is what happens when you use the split function.

    fullName.split(" ")
    
    ["Paul", "Steve", "Panakkal"]
    

    This is not saved to any variable. You can perform the split function and assign an element to a well defined variable like this.

    var firstName = fullName.split(" ")[0];
    
    var lastName = fullName.split(" ")[1];
    
    var otherName = fullName.split(" ")[2];
    
    0 讨论(0)
提交回复
热议问题