3

Suppose all the characters in JavaScript were a, b, c, d, e and f. What I'm trying to do is create a random mapping between characters. So the above might be like

{ `a` : `e`,
  `b` : `b`, 
  `c` : `e`, 
  `d` : `b`,
  `e` : `a`,
  `f` : `c` }

First, how can I get all the possible characters in JavaScript?

var AllChars = new Array(); 
// ... fill AllChars with the full range of characters
user5648283
  • 5,913
  • 4
  • 22
  • 32

2 Answers2

8

Here is an example on how to generate an array with all the lowercase letters:

var AllChars = [];
for (var i=97; i<123; i++)
    AllChars.push(String.fromCharCode(i));

["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]

Edit to include all ascii printable characters per Aaron recommendation:

var AllChars = [];
for (var i=32; i<127; i++)
  AllChars.push(String.fromCharCode(i));

[" ", "!", """, "#", "$", "%", "&", "'", "(", ")", "*", "+", ",", "-", ".", "/", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ":", ";", "<", "=", ">", "?", "@", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "[", "\", "]", "^", "_", "`", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "{", "|", "}", "~"]

Javier Conde
  • 2,553
  • 17
  • 25
2

Here is a one liner for all lowercase chars:

Array(26)
    .fill(97)
    .map((x, y) => String.fromCharCode(x + y))
Enki
  • 1,565
  • 2
  • 13
  • 20