开发者

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

开发者 https://www.devze.com 2023-03-03 17:56 出处:网络
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-ar

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.


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.


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] + " "
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号