在Javascript中,生成隨機(jī)字符串可以使用Math.random()方法和字符串拼接的方式。
隨機(jī)生成指定位數(shù)的字符串
以下代碼可以隨機(jī)生成指定長度的字符串:
function randomString(len) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charLen = characters.length;
for (var i = 0; i < len; i++) {
result += characters.charAt(Math.floor(Math.random() * charLen));
}
return result;
}
調(diào)用該函數(shù)可以生成包含任意字符的隨機(jī)字符串,比如:
randomString(8); randomString(10);
隨機(jī)生成特定類型的字符串
以下代碼可以隨機(jī)生成包含指定類型字符的字符串:
function randomLowerCaseString(len) {
var result = '';
var characters = 'abcdefghijklmnopqrstuvwxyz';
var charLen = characters.length;
for (var i = 0; i < len; i++) {
result += characters.charAt(Math.floor(Math.random() * charLen));
}
return result;
}
function randomUpperCaseString(len) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var charLen = characters.length;
for (var i = 0; i < len; i++) {
result += characters.charAt(Math.floor(Math.random() * charLen));
}
return result;
}
function randomNumberString(len) {
var result = '';
var characters = '0123456789';
var charLen = characters.length;
for (var i = 0; i < len; i++) {
result += characters.charAt(Math.floor(Math.random() * charLen));
}
return result;
}
function randomAlphaNumericString(len) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charLen = characters.length;
for (var i = 0; i < len; i++) {
result += characters.charAt(Math.floor(Math.random() * charLen));
}
return result;
}
分別調(diào)用以上函數(shù)可以生成對應(yīng)類型的隨機(jī)字符串,比如:
randomLowerCaseString(6); randomUpperCaseString(6); randomNumberString(6); randomAlphaNumericString(8);
以上就是Javascript獲取隨機(jī)字符串的方式,希望對你有所幫助。
該文章在 2024/4/12 22:44:09 編輯過