Skip to content

Split full name into first name and last name using apex Salesforce

When Salesforce lead/contact records are being created into Salesforce from an external system, sometimes the full name of the customer is stored in the LastName of the lead or contact object. For example

  • First Name = NULL
  • Last Name = John Smith

So now you want to split the last name which is a full name into the first name and last name. To achieve this, you can write a before insert apex trigger on lead or contact object and can populate the first name and last name field by splitting the last name.

The following function works for a list of lead records and split the last name into first name and last name. You can invoke the following function from a before insert trigger flow.

public static void SplitFullNameIntoFirstAndLast(list<Lead> newLeads){
        
	for(Lead ld : newLeads){
		if(ld.FirstName == NULL){
		
			String FirstName = '';
			String LastName = '';
			
			list<string> NameParts = ld.LastName.split(' ');
			
			if(NameParts?.size() > 1){
				FirstName = NameParts[0];
				for(integer i=1; i<NameParts.size(); i++){
					LastName += NameParts[i]+' ';
				}
				LastName = LastName.trim();
			}else{
				FirstName = ld.FirstName;
				LastName = ld.LastName;
			}
			ld.FirstName = FirstName;
			ld.LastName = LastName;
		}
	}
}

In the above code, the string split method is used to split the lead’s LastName into a list of strings called nameParts, using a space as the delimiter. The first element of the nameParts array is assigned to firstName, while the rest of the elements are assigned to lastName. If the nameParts array has only one element, Firstname is assigned an empty string.