I'd like to shorten some of my code that has different ways of replacing specific patterns that I've set. Basically this code replaces the HTML that I've set as: <span class="combination">0000-AAAA-0000-BBBB</span>
function randomised(len) {
return Math.floor(Math.random() * len);
}
function randomiseStrings(str){
var alphSet = "abcdefghijklmnopqrstuvwxyz";
var numSet = "0123456789";
var alphNumSet = alphSet.concat(numSet);
// 1) Replace 0 with random number.
var str = str.replace(/0/g, function() {
return numSet[randomised(numSet.length)];
});
// 2) Replace A with random number or letter.
var str = str.replace(/A/g, function() {
return alphNumSet[randomised(alphNumSet.length)].toUpperCase();
});
// 3) Replace B with random letter.
var str = str.replace(/B/g, function() {
return alphSet[randomised(alphSet.length)].toUpperCase();
});
return str;
}
$('.combination').text(function(i,t){
return randomiseStrings(t);
});
So as you can see I got 3 identical scripts. However I just couldn't figure out how to do it. What I'm aiming to do is be able to to change these values: str.replace(/[A]/g,, a = alphSet/numSet/alphNumSet and possability to add: .toUpperCase();.
The problem I ended up with what I have no clue how to return these values if I make it as a function. For any suggestion or idea I'd be very thankful.
/[0]/ == /0/and/[A]/ == /A/, etc. You don't need character sets for just one character.return numSet[randomised(numSet.length)];instead of creating a variable. Also definestronly once, not three times. Unless you are going to add much more similiar functions, I would leave it as it is now. Alternative solutions using a generic function won't be as clear as it is now.