Split First name and Last name using javascript

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

    Use this code:

    You'll need to change the line: splitFullName("firstName","lastName","fullName"); and make sure it includes the right field IDs from your form.


    function splitFullName(a,b,c){
        String.prototype.capitalize = function(){
            return this.replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase(); } );
        };
        document.getElementById(c).oninput=function(){
            fullName = document.getElementById(c).value;
            if((fullName.match(/ /g) || []).length ===0 || fullName.substring(fullName.indexOf(" ")+1,fullName.length) === ""){
                first = fullName.capitalize();;
                last = "null";
            }else if(fullName.substring(0,fullName.indexOf(" ")).indexOf(".")>-1){
                first = fullName.substring(0,fullName.indexOf(" ")).capitalize() + " " + fullName.substring(fullName.indexOf(" ")+1,fullName.length).substring(0,fullName.substring(fullName.indexOf(" ")+1,fullName.length).indexOf(" ")).capitalize();
                last = fullName.substring(first.length +1,fullName.length).capitalize();
            }else{
                first = fullName.substring(0,fullName.indexOf(" ")).capitalize();
                last = fullName.substring(fullName.indexOf(" ")+1,fullName.length).capitalize();
            }
            document.getElementById(a).value = first;
            document.getElementById(b).value = last;
        };
        //Initial Values
        if(document.getElementById(c).value.length === 0){
            first = document.getElementById(a).value.capitalize();
            last = document.getElementById(b).value.capitalize();
            fullName =  first + " " + last ;
            console.log(fullName);
            document.getElementById(c).value = fullName;
        }
    }
    
    //Replace the ID's below with your form's field ID's
    splitFullName("firstName","lastName","fullName");
    

    Source: http://developers.marketo.com/blog/add-a-full-name-field-to-a-marketo-form/

    0 讨论(0)
  • 2020-12-08 07:03

    In Spanish it can be tricky because you may have a second optional name and even complex surnames like "del Bosque" or "de la Hoya", vowels with accent marks and the ñ. The following javascript is capabable of parsing a full spanish name, having in count you are writting it respecting the upper and lower cases. It will return a json giving you

    1. name: 1 or 2 main names
    2. lastName: the main lastname
    3. secondLastName: The second lastname

    The code is:

    function parseName(input) {
            var fullName = input || "";
            var result = {};
    
            if (fullName.length > 0) {
                var nameTokens = fullName.match(/[A-ZÁ-ÚÑÜ][a-zá-úñü]+|([aeodlsz]+\s+)+[A-ZÁ-ÚÑÜ][a-zá-úñü]+/g) || [];
    
                if (nameTokens.length > 3) {
                    result.name = nameTokens.slice(0, 2).join(' ');
                } else {
                    result.name = nameTokens.slice(0, 1).join(' ');
                }
    
                if (nameTokens.length > 2) {
                    result.lastName = nameTokens.slice(-2, -1).join(' ');
                    result.secondLastName = nameTokens.slice(-1).join(' ');
                } else {
                    result.lastName = nameTokens.slice(-1).join(' ');
                    result.secondLastName = "";
                }
            }
    
            return result;
    }
    

    The surnames are required if you are going to specify a second name. Try it out with:

    • Eliecer Hernández Garbey
    • Oscar de la Hoya
    • José Julian Martí Pérez
    • Manuel de Céspedes del Castillo
    • Calixto García Íñiguez

    Even try out a complex one like

    • María de la Caridad del Bosque y Loynáz

    Comment your experiences with it.

    0 讨论(0)
  • 2020-12-08 07:03

    Extended version of Speransky Danil's answer which handles the case where the supplied string has only one word in it.

    /**
     * Gets the first name, technically gets all words leading up to the last
     * Example: "Blake Robertson" --> "Blake"
     * Example: "Blake Andrew Robertson" --> "Blake Andrew"
     * Example: "Blake" --> "Blake"
     * @param str
     * @returns {*}
     */
    exports.getFirstName = function(str) {
        var arr = str.split(' ');
        if( arr.length === 1 ) {
            return arr[0];
        }
        return arr.slice(0, -1).join(' '); // returns "Paul Steve"
    }
    
    /**
     * Gets the last name (e.g. the last word in the supplied string)
     * Example: "Blake Robertson" --> "Robertson"
     * Example: "Blake Andrew Robertson" --> "Robertson"
     * Example: "Blake" --> "<None>"
     * @param str
     * @param {string} [ifNone] optional default value if there is not last name, defaults to "<None>"
     * @returns {string}
     */
    exports.getLastName = function(str, ifNone) {
        var arr = str.split(' ');
        if(arr.length === 1) {
            return ifNone || "<None>";
        }
        return arr.slice(-1).join(' ');
    }
    
    0 讨论(0)
  • 2020-12-08 07:04

    If you mean the last name is all the names after the first name, just use:

    var name = "Paul Steve Panakkal";
    var arrName = name.split(" ");
    var firstName = arrName.slice(0, 1).join(' ');
    var lastName = arrName.slice(1, arrName.length).join(' ');
    
    0 讨论(0)
  • 2020-12-08 07:05

    I came up with this logic:

    const fullName = "Paul Steve Panakkal";
    const idx = fullName.lastIndexOf(' ');
    const firstName = idx !== -1 ? fullName.substring(0, idx) : fullName;
    const lastName = idx !== -1 ? fullName.substring(idx + 1) : '';
    console.log('firstName:', firstName, 'lastName:', lastName);
    

    output:

    firstName: Paul Steve lastName: Panakkal
    
    0 讨论(0)
  • 2020-12-08 07:07

    You should use the String.prototype.split() method:

    'Paul Steve Panakkal'.split(' '); // returns ["Paul", "Steve", "Panakkal"]
    

    You can use it this way:

    'Paul Steve Panakkal'.split(' ').slice(0, -1).join(' '); // returns "Paul Steve"
    'Paul Steve Panakkal'.split(' ').slice(-1).join(' '); // returns "Panakkal"
    

    So in common:

    var firstName = fullName.split(' ').slice(0, -1).join(' ');
    var lastName = fullName.split(' ').slice(-1).join(' ');
    
    0 讨论(0)
提交回复
热议问题