Generate random string/characters in JavaScript

2018-12-31 02:19发布

I want a 5 character string composed of characters picked randomly from the set [a-zA-Z0-9].

What's the best way to do this with JavaScript?

30条回答
长期被迫恋爱
2楼-- · 2018-12-31 03:13

let r = Math.random().toString(36).substring(7);
console.log("random", r);

查看更多
怪性笑人.
3楼-- · 2018-12-31 03:13

Something like this should work

function randomString(len, charSet) {
    charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    var randomString = '';
    for (var i = 0; i < len; i++) {
        var randomPoz = Math.floor(Math.random() * charSet.length);
        randomString += charSet.substring(randomPoz,randomPoz+1);
    }
    return randomString;
}

Call with default charset [a-zA-Z0-9] or send in your own:

var randomValue = randomString(5);

var randomValue = randomString(5, 'PICKCHARSFROMTHISSET');
查看更多
后来的你喜欢了谁
4楼-- · 2018-12-31 03:13

The most compact solution, because slice is shorter than substring. Subtracting from the end of the string allows to avoid floating point symbol generated by random function:

Math.random().toString(36).slice(-5);

or even

(+new Date).toString(36).slice(-5);

// Using Math.random
console.log(Math.random().toString(36).slice(-5));

// Using new Date
console.log((+new Date).toString(36).slice(-5));

查看更多
宁负流年不负卿
5楼-- · 2018-12-31 03:13

The simplest way is:

(new Date%9e6).toString(36)

This generate random strings of 5 characters based on the current time. Example output is 4mtxj or 4mv90 or 4mwp1

The problem with this is that if you call it two times on the same second, it will generate the same string.

The safer way is:

(0|Math.random()*9e6).toString(36)

This will generate a random string of 4 or 5 characters, always diferent. Example output is like 30jzm or 1r591 or 4su1a

In both ways the first part generate a random number. The .toString(36) part cast the number to a base36 (alphadecimal) representation of it.

查看更多
谁念西风独自凉
6楼-- · 2018-12-31 03:13

If you are using Lodash or Underscore, then it so simple:

var randomVal = _.sample('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', 5).join('');
查看更多
姐姐魅力值爆表
7楼-- · 2018-12-31 03:13

How about something like this: Date.now().toString(36) Not very random, but short and quite unique every time you call it.

查看更多
登录 后发表回答