generate random string for div id

后端 未结 12 699
旧时难觅i
旧时难觅i 2020-12-04 17:03

I want to display YouTube videos on my website, but I need to be able to add a unique id for each video that\'s going to be shared by users. So I put this toget

相关标签:
12条回答
  • 2020-12-04 17:54

    window.btoa(String.fromCharCode(...window.crypto.getRandomValues(new Uint8Array(5))))

    Using characters except ASCII letters, digits, '_', '-' and '.' may cause compatibility problems, as they weren't allowed in HTML 4. Though this restriction has been lifted in HTML5, an ID should start with a letter for compatibility.

    0 讨论(0)
  • 2020-12-04 17:55

    2018 edit: I think this answer has some interesting info, but for any practical applications you should use Joe's answer instead.

    A simple way to create a unique ID in JavaScript is to use the Date object:

    var uniqid = Date.now();
    

    That gives you the total milliseconds elapsed since January 1st 1970, which is a unique value every time you call that.

    The problem with that value now is that you cannot use it as an element's ID, since in HTML, IDs need to start with an alphabetical character. There is also the problem that two users doing an action at the exact same time might result in the same ID. We could lessen the probability of that, and fix our alphabetical character problem, by appending a random letter before the numerical part of the ID.

    var randLetter = String.fromCharCode(65 + Math.floor(Math.random() * 26));
    var uniqid = randLetter + Date.now();
    

    This still has a chance, however slim, of colliding though. Your best bet for a unique id is to keep a running count, increment it every time, and do all that in a single place, ie, on the server.

    0 讨论(0)
  • 2020-12-04 18:02

    I also needed a random id, I went with using base64 encoding:

    btoa(Math.random()).substring(0,12)
    

    Pick however many characters you want, the result is usually at least 24 characters.

    0 讨论(0)
  • 2020-12-04 18:02

    Or you could use Cripto since it's already built in(except in IE11, I swear these guys havent updated in years!)

    https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues#Examples

    var id = new Uint32Array(10);
    window.crypto.getRandomValues(array);
    

    I also found this:

    https://gist.github.com/6174/6062387#gistcomment-3255605

    let length = 32;
    let id = crypto.randomBytes(length).toString("base64");
    

    There's a lot of ways to do this, but for most people, there's no reason to reinvent the wheel :)

    0 讨论(0)
  • 2020-12-04 18:04

    I really like this function:

    function guidGenerator() {
        var S4 = function() {
           return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
        };
        return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
    }
    

    From Create GUID / UUID in JavaScript?

    0 讨论(0)
  • 2020-12-04 18:07

    A edited version of @jfriend000 version:

        /**
         * Generates a random string
         * 
         * @param int length_
         * @return string
         */
        function randomString(length_) {
    
            var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghiklmnopqrstuvwxyz'.split('');
            if (typeof length_ !== "number") {
                length_ = Math.floor(Math.random() * chars.length_);
            }
            var str = '';
            for (var i = 0; i < length_; i++) {
                str += chars[Math.floor(Math.random() * chars.length)];
            }
            return str;
        }
    
    0 讨论(0)
提交回复
热议问题