Home > Web Front-end > JS Tutorial > How Can I Generate Globally Unique Identifiers (GUIDs) in JavaScript Reliably Across Different Platforms?

How Can I Generate Globally Unique Identifiers (GUIDs) in JavaScript Reliably Across Different Platforms?

Patricia Arquette
Release: 2024-12-24 18:22:16
Original
264 people have browsed it

How Can I Generate Globally Unique Identifiers (GUIDs) in JavaScript Reliably Across Different Platforms?

Generating Globally-Unique Identifiers (GUIDs) in JavaScript

Creating globally-unique identifiers (GUIDs) in JavaScript presents challenges related to platform availability, randomness, and ASCII compatibility. To address these concerns, several approaches are available:

Modern Browsers and Secure Contexts:

If the application is running on a modern browser with a secure connection (HTTPS or localhost), the crypto.randomUUID() method is a reliable and efficient option for generating RFC4122-compliant UUIDs. This method ensures randomness and satisfies the required ASCII character range.

Legacy Platforms and Non-Secure Contexts:

For platforms without crypto.randomUUID() or in non-secure contexts, the uuid package is a well-supported alternative that can generate UUIDs meeting various specifications.

Fallback Method:

If neither of the above options is available, a fallback method can be employed:

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

This method utilizes crypto.getRandomValues() to generate random numbers and ensures adherence to the ASCII character range.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template