0

I have a String

var letters="ABCDEFGHIJK";

How i can pick 4 random characters from that. with Math.random() or something else?

The output should spend something like that:

DAKF or FAHG ...

Best regards

dolu28
  • 31
  • 2
  • 8

3 Answers3

0

You can shuffle and pick top 4 (or last 4) characters

var shuffled = (str) => str.split('').sort(function() {
  return 0.5 - Math.random();
}).join('');
var letters = "ABCDEFGHIJK";

console.log(shuffled(letters).slice(-4)); //last 4

console.log(shuffled(letters).slice(-4));  //last 4
 
console.log(shuffled(letters).substring(0,4));  //top 4
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
0

If multiple instances are same characters are allowed , the implementation could be like this:

var letters="ABCDEFGHIJK";
var arr=letters.split("");
var str="";
var num=0;
while(num<4){
    str+=arr[Math.floor(Math.random()*10)];
    num++;
}
console.log(str);

In case you wanted unique letters from Math.random:

var letters="ABCDEFGHIJK";
var arr=letters.split("");
var str="";
var num=0;
while(num<4){
var char=arr[Math.floor(Math.random()*10)];
 if(str.includes(char)){
   continue;
 }
 else{
   str+=char;
   num++;
 }
}
console.log(str);
0

I would make your letters an array and use following code:

var letters=["A","B","C","D","E","F","G","H","I","J","K"];

for (i = 0; i < 4; i++){
var number = Math.floor((Math.random() * 10));
console.log(letters[number]);
}

If you want the letters displayed behind each other create a new variable and concatenate the letters in the new variable each time you loop it.

mrdeadsven
  • 744
  • 1
  • 9
  • 22