Home >Web Front-end >JS Tutorial >How Can I Generate Globally Unique Identifiers (GUIDs/UUIDs) in JavaScript?

How Can I Generate Globally Unique Identifiers (GUIDs/UUIDs) in JavaScript?

DDD
DDDOriginal
2024-12-20 16:27:20411browse

How Can I Generate Globally Unique Identifiers (GUIDs/UUIDs) in JavaScript?

Creating Globally Unique Identifiers in JavaScript

In the realms of JavaScript, the task of generating globally unique identifiers (GUIDs) or universally unique identifiers (UUIDs) often arises. These identifiers serve as unique representations for entities or resources within a system, ensuring their distinctiveness.

Approach 1: Native Browser API for Secure Environments

If your application operates within secure contexts (localhost, HTTPS), the crypto.randomUUID() method offers a reliable option. This API is widely supported in modern browsers and JS runtimes. However, it is essential to note that its availability is limited to secure contexts.

Approach 2: uuid Module

For scenarios where secure contexts are not available or if compatibility with legacy platforms is required, the uuid module presents a robust solution. This module has undergone extensive testing and provides support for generating UUIDs of various versions.

Approach 3: Custom Generation

If neither of the above approaches meet your requirements, consider this custom method:

function uuidv4() {
  return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, c =>
    (+c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> +c / 4).toString(16)
  );
}

console.log(uuidv4());

This method relies on the crypto.getRandomValues function to introduce randomness into the UUID. It iterates through a predefined character set and manipulates it based on cryptographic values.

The above is the detailed content of How Can I Generate Globally Unique Identifiers (GUIDs/UUIDs) in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:My React Journey: Day 12Next article:My React Journey: Day 12