Home > Web Front-end > JS Tutorial > How to generate UUID with two lines of Javascript code

How to generate UUID with two lines of Javascript code

hzc
Release: 2020-06-15 09:42:09
forward
3609 people have browsed it

Discover an easy way to generate UUIDs in a Javascript application without relying on third-party libraries.

function uuid() {
  var temp_url = URL.createObjectURL(new Blob());
  var uuid = temp_url.toString(); // blob:https://xxx.com/b250d159-e1b6-4a87-9002-885d90033be3
  URL.revokeObjectURL(temp_url);
  return uuid.substr(uuid.lastIndexOf("/") + 1);
}
Copy after login

The URL.createObjectURL method can be used in Javascript to create a unique URL that represents the object passed to it. In order to make this URL unique, the URL returned by the URL.createObjectURL method will carry a 36-bit long string, which is the same length as the UUID. Through this principle, the UUID can be simulated.

Here are some examples of UUIDs generated by this method:

for (var i = 0; i < 10; ++i) {
  console.log(uuid());
}

// 执行结果如下
// f6ca05c0-fad5-46fc-a237-a8e930e7cb49
// 6a88664e-51e1-48c3-a85e-7bf00467e9e6
// e6050f4c-e86d-4081-9376-099bfbef2c30
// bde3da3c-b318-4498-8a03-9a773afa84bd
// ba0fda03-f806-4c2f-b6f5-1e74a299e603
// 62b2edc3-b09f-4bf9-8dbf-c4d599479a29
// e70c0609-22ad-4493-abcc-0e3445291397
// 920255b2-1838-497d-bc33-56550842b378
// 45559c64-971c-4236-9cfc-706048b60e70
// 4bc4bbb9-1e90-432b-99e8-277b40af92cd
Copy after login


Note: The purpose of URL.createObjectURL is not to generate random UUIDs. Therefore, the above method of generating UUIDs may cause side effects that I am not yet aware of. If you can think of any questions, please leave a message and reply to me, thank you.

Recommended tutorial: "JS Tutorial"

The above is the detailed content of How to generate UUID with two lines of Javascript code. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:juejin.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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template