Search code examples
zapier

Using Zapier Code to Split a Full Name into First Name Last Name


We are using a webhook to pull data from Vimeo to Zapier and send it to our CRM (InfusionSoft).

I have no experience with coding and am having issues running a simple JS script in Zapier Code. The goal is to split up an embedded customer name, which comes as First and Last Name, into two outputs, First Name, Last Name.

The code that I found, and tried, from Zapier is this:

if ' ' in input['fullName']:
    first, last = input['fullName'].split(' ', 1)
else:
    first, last = input['fullName'], None # fallback
return {
    'firstName': first,
    'lastName': last
}

Any help here is greatly appreciated!

Thanks, Morgan

Zapier Code Error Returned


Solution

  • This is the Javascript version of your code. You can just change null to whatever value you want in the else clause.

    let first, last;
    if ( input['fullName'].indexOf(" ") != -1 )
        [first, last] = input['fullName'].split(' ', 2);
    else
        [first, last] = [input['fullName'], null];
    return {
        'firstName': first,
        'lastName': last
    }
    

    For your later problem. I think it because you use this as raw and not in a function thus, I will write a fix for you. For Zapier, their document said all your values and variables start with inputData. So to apply the code above raw and not in a function call then you would have to do this.

    if ( inputData.fullName ) {
        let first, last;
        if ( inputData['fullName'].indexOf(" ") != -1 )
            [first, last] = inputData['fullName'].split(' ', 2);
        else
            [first, last] = [inputData['fullName'], null];
        return {
            'firstName': first,
            'lastName': last
        }
    } else {
        // inputData.fullName is not available, do something else.
    }
    

    If you are going to use it in a function call, then follow the below:

    function getFullName(inputData) {
        var first, last;
        if ( inputData['fullName'].indexOf(" ") != -1 )
            [first, last] = inputData['fullName'].split(' ', 2);
        else
            [first, last] = [inputData['fullName'], null];
        return {
            'firstName': first,
            'lastName': last
        }
    }
    
    if ( inputData.fullName ) { 
       var someobject = getFullName(inputData);
    } else {
       // no inputData.fullName
    }