How to generate a random string from ASCII characters in JavaScript

MrFrontend :

How can I build a simple string generator that creates and prints out a randomized string of 10 characters, including lowercase and uppercase letters, numbers and special characters from 0 to 127 of the ASCII table by typing the ASCII-character-number-range in the method? Not a variable like

    var possibleCharacters = "01234567890abcdefgh....."

A friend of me already built it in Java (see below), so how can I build that in JavaScript, also with a for-loop like in the Java example?

    public class Main {
public static void main(String[] args) {
    for (int counter = 0; counter <= 9; counter++) {
        int randomNum = 0 + (int)(Math.random() * 127);
        if(randomNum > 33) {
            System.out.print((char)randomNum);
        }else {
            counter--;
        }
    }
}
}

It should just generate something like "_e7N?:G&M0" i.e.

shrys :

A function to return the random string:

function getString() {
  var str = "";
  for (counter = 0; counter <= 9; counter++) {
    var randomNum = 0 + parseInt(Math.random() * 127);
    if (randomNum > 33) {
      str += String.fromCharCode(randomNum);
    } else {
      counter--;
    }
  }
  return str;
}
for (i = 0; i < 10; i++)
  console.log(getString());

If you're attempting to generate numbers between 33 and 127:

function getString() {
  var str = "";
  for (counter = 0; counter <= 9; counter++) {
    var randomNum = 0 + parseInt(Math.floor(Math.random() * (127 - 33 + 1) + 33));
    str += String.fromCharCode(randomNum);
  }
  return str;
}
for (i = 0; i < 10; i++)
  console.log(getString());

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=164603&siteId=1