如何在NodeJ中将字符串转换为UUID v4?

biswetbf  于 2022-12-12  发布在  Node.js
关注(0)|答案(2)|浏览(148)

假设下面有一个字符串:

const input = '83e54feeeb444c7484b3c7a81b5ba2fd';

我的理想输出是uuid v4:

83e54fee-eb44-4c74-84b3-c7a81b5ba2fd

关于解决办法,我只想出了这个主意:

function insertString(str, index, value) {
    return str.substr(0, index) + value + str.substr(index);
}

function converToUUID(_uuid){
 _uuid = insertString(_uuid, 8, '-')
 _uuid = insertString(_uuid, 13, '-')
 _uuid = insertString(_uuid, 18, '-')
 _uuid = insertString(_uuid, 23, '-')
 
 return _uuid
}

console.log(converToUUID(a))

有没有一种方法可以通过不一直调用insertString函数来获得理想的输出?
感谢您的帮助!

acruukt9

acruukt91#

我会使用正则表达式

const input = '83e54feeeb444c7484b3c7a81b5ba2fd';
const output = input.replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/g, '$1-$2-$3-$4-$5')
console.log(output)
mf98qq94

mf98qq942#

const uuidRx = new RegExp(/([a-zA-Z0-9]{8})([a-zA-Z0-9]{4})([a-zA-Z0-9]{4})([a-zA-Z0-9]{5})([a-zA-Z0-9]{11})/);
const str = "83e54feeeb444c7484b3c7a81b5ba2fd";
const uuid = str.replace(uuidRx, "$1-$2-$3-$4-$5");
console.log(uuid);

相关问题