Martyboy
Martyboy

Reputation: 370

replace each selected value with random letter/number

So I'm wondering how can I for example go over each specific text or number I've set and change them. For example I have:

0000-0000

and I want to replace each 0 with some input I've set. For Example:

1111-1111

I'm trying create random serial code kind of script so I'd just like to start of by how to do that.

Thanks in advance.

Edit: So this is how I would generate the random number or letter, just gotta go trough each zeros to replace them with random value:

jQuery(document).ready(function ($) {
    function randomAlphaNumber() {
        var values = "abcdefghijklmnopqrstuvwxyz0123456789";

        rN = values.charAt(Math.floor(Math.random() * values.length));

        return rN;
    }

    $(".combination").html(randomAlphaNumber());

});

Upvotes: 0

Views: 1030

Answers (1)

David Thomas
David Thomas

Reputation: 253396

At its simplest I'd suggest:

function randomiseString(str){
    var chars = "abcdefghijklmnopqrstuvwxyz0123456789";
    var _str = str.replace(/[^-]/g,function(a){
        return chars[Math.floor(Math.random() * chars.length)];
    });
    return _str;
}

$('.combination').text(function(i,t){
    return randomiseString(t);
});

JS Fiddle demo.

If you also want to use upper, and lower, case letters:

function randomised(len) {
    return Math.floor(Math.random() * len);
}

function randomiseString(str){
    var chars = "abcdefghijklmnopqrstuvwxyz0123456789";
    var _str = str.replace(/[^-]/g,function(a){
        return chars[randomised(chars.length)][randomised(2) == 0 ? 'toUpperCase' : 'toLowerCase']();
    });
    return _str;
}

$('.combination').text(function(i,t){
    return randomiseString(t);
});

JS Fiddle demo.

Upvotes: 3

Related Questions