Split First name and Last name using javascript

后端 未结 20 3025
悲&欢浪女
悲&欢浪女 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:42

    use JS split with space as delimitter.

    https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/split

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

    I think, it's time to get started with regular expressions :)

    "Paul Steve Panakkal".split(/(\s).+\s/).join("") // "Paul Panakkal"
    
    0 讨论(0)
  • 2020-12-08 06:44

    I tried below code and it works cool for me

    var full_name = 'xyz abc pqr';
    var name = full_name.split(' ');
    var first_name = name[0];
    var last_name = full_name.substring(name[0].length.trim());
    

    In above example:

    (1)

    If full_name = 'xyz abc pqr';
    first_name = "xyz";
    last_name = "abc pqr";
    

    (2)

    If `full_name = "abc"`:
    Then first_name = "abc";
    and last_name = "";
    
    0 讨论(0)
  • 2020-12-08 06:44

    const fullName = 'Paul Steve Panakkal'.split(' ');
    const lastName = fullName.pop(); // 'Panakkal'
    const firstName = fullName.join(' '); // 'Paul Steve'
    console.log(firstName);
    console.log(lastName);

    0 讨论(0)
  • 2020-12-08 06:45
    "  Paul Steve   ".trim().split(/(\s).+\s/).join("")  // 'Paul Steve'
    

    You should add trim() just in case the user accidentally types an extra whitespace!

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

    A comenter said What if want first name to be "Paul" and last name "Steve Panakkal"

    var name = "Paul Steve Panakkal" // try "Paul", "Paul Steve"
    var first_name = name.split(' ')[0]
    var last_name = name.substring(first_name.length).trim()
    console.log(first_name)
    console.log(last_name)

    0 讨论(0)
提交回复
热议问题