FLASH SALE Get 20% OFF everything using the coupon code: FLASH20 View WordPress Plugins →

JavaScript Random String Generator

on in JavaScript DOM
Last modified on

I needed a random string for various purposes. For example, to provide a unique ID to HTML elements via JavaScript. The code below is a semi-random string generator function.

let guid = function () {
    let S4 = function () {
        return (((1 + Math.random()) * 0x10000)|0).toString(16).substring(1);
    };

    return (S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4());
};

It should return random strings, similar to the ones below:

ff31943b-0818-6651-d3a5-9ffb43a5d410
542b312d-8b63-9327-c25e-2423fd93c797
c49d26a2-cc0a-99ff-df6c-f8cd5f7d9f60
beeb0e19-65ee-664f-a953-0e99288b03ec

Related posts

Leave a Reply

Your email address will not be published. Required fields are marked *