如何在表单字段输入中生成短的唯一代码?

时间:2015-02-10 01:49:16

标签: javascript php jquery html

您好我有这个脚本在页面加载时将唯一代码加载到表单输入字段。只有它产生一个长值。如何将此值缩短为字符大小的一半。

示例代码: adf4a039-7c9d-4642-94f2-0569910a4a10

SCRIPT

<script>
$(document).ready(function() {
function invoiceid() {
    var d = new Date().getTime();
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = (d + Math.random()*16)%16 | 0;
        d = Math.floor(d/16);
        return (c=='x' ? r : (r&0x3|0x8)).toString(16);
    });
    return uuid;
};

document.getElementById('invoiceid').onclick = function() {
    document.getElementById('uuid').innerHTML = invoiceid();
};

document.getElementById('uuid').innerHTML = invoiceid();

});

</script>

3 个答案:

答案 0 :(得分:3)

XXXXX的{​​{1}}为replaced,因此您生成的X越大/越小ID

function invoiceid() {
    var d = new Date().getTime();
    // Remove some of the X's to generate a smaller ID 
// You can also remove '-' if you don't want the ID formatted in sections
    var uuid = 'xxxx-xxxx4xx'.replace(/[xy]/g, function(c) {
        var r = (d + Math.random()*16)%16 | 0;
        d = Math.floor(d/16);
        return (c=='x' ? r : (r&0x3|0x8)).toString(16);
    });
    document.getElementById('uuid').innerHTML=uuid;
    //return uuid;
}
 window.onload=invoiceid;
<div id="uuid"></div><button onclick="invoiceid()">New ID</button>

快乐的编码!

答案 1 :(得分:2)

我正在努力解决的问题是,简单地缩短它会破坏UUID的惯例。但是,如果你真的想,你可以简单地substr() ......

var shortId = invoiceid().substr(0, 18);

但请注意,这会增加重复值的可能性。使用此方法可能需要您检查具有相同值的先前发票ID。

完整代码(针对jQuery更新):

<script>
$(document).ready(function() {
function invoiceid() {
    var d = new Date().getTime();
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = (d + Math.random()*16)%16 | 0;
        d = Math.floor(d/16);
        return (c=='x' ? r : (r&0x3|0x8)).toString(16);
    });
    return uuid;
};

function shortInvoiceId() {
    return invoiceid().substr(0, 18);
}

$('#invoiceid').on('click', function() {
    $('#uuid').html(shortInvoiceId());
});

$('#uuid').html(shortInvoiceId());

});

</script>

http://jsfiddle.net/to52rrt9/2/

答案 2 :(得分:1)

我同意之前的评论 - 如果独特对此非常重要,那么您应该坚持使用UUID。如果您只想生成随机查找代码,请参阅this answer及相关答案,了解在JavaScript中生成随机字母数字的多种方法。例如:

<script>

function randomString(len, charSet) {
    charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    var randomString = '';
    for (var i = 0; i < len; i++) {
        var randomPoz = Math.floor(Math.random() * charSet.length);
        randomString += charSet.substring(randomPoz,randomPoz+1);
    }
    return randomString;
}

$(document).ready(function() {
document.getElementById('invoiceid').onclick = function() {
    // random 5-character string
    document.getElementById('uuid').innerHTML = randomString(5); 
};

document.getElementById('uuid').innerHTML = randomString(5);

});

</script>