Split First name and Last name using javascript

后端 未结 20 3209
悲&欢浪女
悲&欢浪女 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: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" --> ""
     * @param str
     * @param {string} [ifNone] optional default value if there is not last name, defaults to ""
     * @returns {string}
     */
    exports.getLastName = function(str, ifNone) {
        var arr = str.split(' ');
        if(arr.length === 1) {
            return ifNone || "";
        }
        return arr.slice(-1).join(' ');
    }
    

提交回复
热议问题