Split First name and Last name using javascript

后端 未结 20 3028
悲&欢浪女
悲&欢浪女 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 06:50

    You needn't use any split method and create unnecessary arrays for that operation. Just use lastIndexOf and substring methods of javascript.

    var s = "Paul Steve Panakkal";
    var a = s.lastIndexOf(' '); // last occurence of space
    var b = s.substring(0, a); // Paul Steve
    var c = s.substring(a+1); // Panakkal
    
    0 讨论(0)
  • 2020-12-08 06:51

    Use the following code, it works for me

    let name = "Paul Steve Panakkal"
    let parts = name.split(' ')
    let firstName = parts.shift();  // Paul
    let lastName = parts.join(' '); // Steve Panakkal
    
    console.log({
    firstName,
    lastName
    })

    0 讨论(0)
  • 2020-12-08 06:52

    if you assume the last word is the last name and a single word name is also a last name then ...

    var items = theName.split(' '),
        lastName = items[items.length-1],
        firstName = "";
    
    for (var i = 0; i < items.length - 1; i++) {
       if (i > 0) {
          firstName += ' ';
       }
       firstName += items[i];
    }
    
    0 讨论(0)
  • 2020-12-08 06:53
    var firstName = fullName.split(" ")[0];
    
    0 讨论(0)
  • 2020-12-08 06:58

    Yes:

    var fullName = "Paul Steve Panakkal".split(' '),
        firstName = fullName[0],
        lastName = fullName[fullName.length - 1];
    

    References:

    • string.split().
    0 讨论(0)
  • 2020-12-08 06:58

    This way, both firstName and lastName are always correct

    var names = fullName.split(' ');
    if (!names || names.length <= 1) {
       firstName = this.name;
       lastName = '';
    } else {
       firstName = names.slice(0, -1).join(' ');
       lastName = names.slice(-1).join(' ');
    }
    
    0 讨论(0)
提交回复
热议问题