简体   繁体   中英

Javascript Concatenate FirstName, LastName and Code

I am trying to concatenate the first letter of both names onto the randomly generated code.

   var firstname = prompt("Please enter your first name.");
   var lastname = prompt ("Please enter your last name.");

   if (amountCorrect >= 4){
            alert("Your login Code for the store is: " + str(firstname,1,1) + str(lastname,1,1) + (generateCode())); // Do the generateCode function
        }
        else{
            alert("You have not passed on this occasion. You will now be taken back to the homepage.");
            window.history.go(-1); // Go back a step
        }
    }

    function generateCode(){

    var text        = "";
    var possible    = "0123456789";

    for( var i=0; i < 4; i++ ){
        text += possible.charAt(Math.floor(Math.random() * possible.length));   
    }

    return text;
}

You can use substring to extract the first character:

alert("Your login Code for the store is: " + firstname.substring(0,1) + lastname.substring(0,1) + (generateCode()));

Here is the documentation for String.prototype.substring .

There is no definition for 'str' used within your alert line..

alert("Your login Code for the store is: " + firstname[0] + lastname[0] + (generateCode()));

The above should work. It also looks like you have a stray } after the if block. You should probably also be doing more error checking for the user input, if the user doesn't enter a value at the prompt for example, you will get undefinedundefined#### where #### is the generated code.

Replace the line

alert("Your login Code for the store is: " + str(firstname,1,1) + str(lastname,1,1) + (generateCode())); // Do the generateCode function

with

alert("Your login Code for the store is: " + firstname.substring(1, 0) + lastname.substring(1, 0) + (generateCode())); // Do the generateCode function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM