Js/JQuery生成不重复的UUID

2023-03-06 16:24:30 浏览数 (1)

javascript代码

代码语言:javascript复制
function guid () {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0
        var v = c === 'x' ? r : (r & 0x3 | 0x8)
        return v.toString(16)
    })
}

去除横线

代码语言:javascript复制
function guidShort () {
    return guid ().replace("-","");
}

显示结果

代码语言:javascript复制
UUID完整:4915d2f4-2e83-47d6-bc76-e321caeff812
UUID不含-:f5e53a50fda8-4c8d-a4fb-04821ac932d0

完整Demo

代码语言:javascript复制
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
    function guid () {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0
        var v = c === 'x' ? r : (r & 0x3 | 0x8)
        return v.toString(16)
    })
}

function guidShort () {
    return guid ().replace("-","");
}

$(function(){ 
    $("#div1").text('UUID完整:' guid ());
    $("#div2").text('UUID不含-:' guidShort ());
});

    
</script>
</head>

<body>
    <div id="div1"></div>
    <div id="div2"></div>
</body>
</html>

0 人点赞