Home >Web Front-end >JS Tutorial >JavaScript generates one-time password (OTP)
A one-time password (OTP) is a password that is valid for only one login session or transaction on a computer or digital device. Nowadays, almost all services such as online banking and online transactions use OTP. They are usually a combination of 4 or 6 digits or 6 alphanumeric digits. The random function is used to generate random OTPs predefined in the math library. This article will introduce to you how to use JavaScript to generate OTP. (Recommended: "javascript tutorial")
Function:
##random():This function returns 0 to 1 any random number between.
floor():It returns the floor of any floating point number as an integer value.
Example 1: Generate 4-digit OTP:
<script> function generateOTP() { // 声明一个存储所有数字的digits变量 var digits = '0123456789'; let OTP = ''; for (let i = 0; i < 4; i++ ) { OTP += digits[Math.floor(Math.random() * 10)]; } return OTP; } document.write("4位OTP: ") document.write( generateOTP() ); </script>Output:
4位OTP: 2229
Example 2: Generate 6-digit number OTP:
<script> function generateOTP() { var digits = '0123456789'; let OTP = ''; for (let i = 0; i < 6; i++ ) { OTP += digits[Math.floor(Math.random() * 10)]; } return OTP; } document.write("6位OTP: ") document.write( generateOTP() ); </script>Output:
6位OTP: 216664
Example 3: Generate alphanumeric OTP of length 6:
<script> function generateOTP() { //声明一个存储所有字符串的string变量 var string = '0123456789abcdefghijklmnopqrs tuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; let OTP = ''; //求字符串的长度 var len = string.length; for (let i = 0; i < 6; i++ ) { OTP += string[Math.floor(Math.random() * len)]; } return OTP; } document.write("长度为6的OTP: ") document.write( generateOTP() ); </script>Output :
长度为6的OTP: rab0TjThis article is a specific introduction to JavaScript to generate one-time passwords (OTP). I hope it will be helpful to friends in need!
The above is the detailed content of JavaScript generates one-time password (OTP). For more information, please follow other related articles on the PHP Chinese website!