Standalone UUID generator in JavaScript

栏目: IT技术 · 发布时间: 5年前

内容简介:12 June 2020 (Updated: 12 June 2020)Here is a simple and easy (no external dependencies) method to generateThe
<a href="../index.html">Home</a> > <a href="../blog.html">Blog</a>

Standalone UUID generator in Javascript

12 June 2020 (Updated: 12 June 2020)

Here is a simple and easy (no external dependencies) method to generate UUID in your Javascript applications.

// Author: Abhishek Dutta, 12 June 2020
// License: CC0 (https://creativecommons.org/choose/zero/)
function uuid() {
  var temp_url = URL.createObjectURL(new Blob());
  var uuid = temp_url.toString();
  URL.revokeObjectURL(temp_url);
  return uuid.substr(uuid.lastIndexOf('/') + 1); // remove prefix (e.g. blob:null/, blob:www.test.com/, ...)
}

The URL.createObjectURL() static method available in Javascript creates a unique URL to represent an object passed to it as a parameter. The uuid() method uses this property of URL.createObjectURL() to generate unique URL -- which is a random UUID in all the browsers that I have tested so far -- on empty objects. Here are some example UUID 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

Note: The intended purpose of URL.createObjectURL() is not to generate random UUID. So, the above method of generating UUID may cause side effects that I am not yet aware of. If you can think of any issues, please let me know .

Updates:

  • one800higgins : this works because generating a UUID for the blob URL is part of the spec .
  • DrDuPont : Here's the file API working draft from 2010. The outputted URI was slated to be a UUID from the beginning.

以上所述就是小编给大家介绍的《Standalone UUID generator in JavaScript》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

他们以为自己很厉害:12个企业管理陷阱

他们以为自己很厉害:12个企业管理陷阱

[法] 克里斯蒂娜•凯德朗 / 王倩 / 人民邮电出版社 / 2018-11 / 69.00元

本书讲述了震惊世界的150个企业管理失败案例,并从产品与服务定位、技术 创新、广告与营销策略、跨文化发展、融资战略到企业文化与员工管理等众多角度, 揭露了商场各种败局的内幕。作者以风趣的笔触讲述了国际知名企业和商界精英们 的惨痛教训,又以专业角度解读了这些失利背后的经济学和管理学因素,给读者带 来了启示。一起来看看 《他们以为自己很厉害:12个企业管理陷阱》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

URL 编码/解码
URL 编码/解码

URL 编码/解码