Mark Walters
Mark Walters

Reputation: 12390

how to split a string with javascript - Separate first name and surname from textbox

I'm using the following code to split up surname from first + middle names and place them in three seperate fields. One holds the surname, one holds the firstnames and one holds all of them but re-arranged as lastname, firstname(s)

function switchName(ele){
        var splitName = ele.value.split(" ");
        var surname = splitName[splitName.length-1]; //The last one
        var firstnames 
        for (var i=0; i < splitName.length-1; i++){
                firstnames += splitName[i] + " "
                }

    document.getElementById("hdnSNFNS").value = surname + ", " + firstnames;
    document.getElementById("hdnEmployeeSurname").value = surname;
    document.getElementById("hdnEmployeeFirst").value = firstnames;

It works as is but I get this output for the firstnames

Stone, undefinedJoss Helen

I've played around with it for ages but cant stumble across the correct solution.

Upvotes: 0

Views: 5350

Answers (2)

dee-see
dee-see

Reputation: 24078

You're missing a ; on the 4th line line and you should initialize firstnames to an empty string.

var firstnames = "";.

Right now, the first iteration of your loop concatenates the first name to an uninitialized variable and that's where the undefined comes from. With the initialization you'll concatenate with "nothing" and it will produce the expected result.

Upvotes: 2

Raynos
Raynos

Reputation: 169383

function switchName(ele){
    var splitName = ele.value.split(" ");
    var surname = splitName[splitName.length-1]; //The last one
    var firstnames = ""; // <- forgot to initialize to an empty string
    for (var i=0; i < splitName.length-1; i++){
        firstnames += splitName[i] + " "
    }
}

Upvotes: 1

Related Questions