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
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(' ');
}