So I saw another solution on here with a problem I was having. Though the problem isn't completely solved for me.
This is the code that I found on here.
function makeid(length) {
var result = "";
var characters = '0123456789';
for (var i = 0; i < length; i ) {
result = characters[Math.floor(Math.random() * characters.length)];
}
result = result.match(/\d{1,4}/g).join("-");
return result;
}
console.log(makeid(16));
And this is the current code I have now.
function makeid(length) {
var result = "";
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
for (var i = 0; i < length; i ) {
result = characters[Math.floor(Math.random() * characters.length)];
}
result = result.match(/\d{1,4}/g).join("-");
return result;
}
console.log(makeid(16));
The output is not want I want. I want the output to be in both Letters and Numbers and I'm not sure why it won't do both!
CodePudding user response:
It's because your match()
is only looking for digits ( \d
) and not any character ( .
):
function makeid(length) {
var result = "";
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
for (var i = 0; i < length; i ) {
result = characters[Math.floor(Math.random() * characters.length)];
}
result = result.match(/.{1,4}/g).join("-");
return result;
}
console.log(makeid(15));
And you can get rid of slow match
all together, by using %
operator:
function makeid(length) {
var result = "";
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
for (var i = 0; i < length; i ) {
result = characters[Math.floor(Math.random() * characters.length)];
if (i 1 < length && !((i 1) % 4))
result = "-";
}
return result;
}
console.log(makeid(16));