How to generate GUID/UUID?
P粉304704653
P粉304704653 2023-10-08 14:55:18
0
2
497

How to create a GUID (Globally Unique Identifier) in JavaScript? GUIDs/UUIDs should be at least 32 characters long and should stay within the ASCII range to avoid trouble passing them.

I'm not sure what routines are available on all browsers, what the "randomness" of the built-in random number generator is, how it is seeded, etc.

P粉304704653
P粉304704653

reply all (2)
P粉352408038

[Edited on March 5, 2023 to reflect the latest best practices for generating RFC4122-compliant UUIDs]

crypto.randomUUID()is now standard on all modern browsers and JS runtimes. However, becausenew browser APIs are restricted to secure contexts, this method is only available to pages served locally (localhostor127.0.0.1) or over HTTPS.

For readers interested in other UUID versions, generating UUIDs on legacy platforms or in non-secure contexts, there istheuuidmodule. It is well-tested and supported.

If the above method fails, there is also this method (based on the original answer to this question):

function uuidv4() { return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c => (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16) ); } console.log(uuidv4());

Note:The use ofanyUUID generator that relies onMath.random()is strongly discouraged(including snippets featured in previous versions of this answer ) forreasons best explained here.TL;DR:solutions based onMath.random()do not provide good uniqueness guarantees.

    P粉190443691

    A UUID (Universally Unique Identifier), also known as a GUID (Globally Unique Identifier), according toRFC 4122is an identifier designed to provide certain uniqueness guarantees.

    While it is possible to implement an RFC-compliant UUID with a few lines of JavaScript (e.g., see@broofa's answer, below) there are several common pitfalls:

    • Invalid id format (UUIDs must be of the form "xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx", where x is one of [0-9, a-f]Mis one of [1-5], andNis [8, 9, a, or b]
    • Use of a low-quality source of randomness (such asMath.random)

    Therefore, developers writing code for production environments are encouraged to use strict, well-maintained implementations such as theuuid module.

      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!