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
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
Share
Improve this question
asked Jan 21, 2016 at 16:27
user5648283user5648283
6,2135 gold badges28 silver badges35 bronze badges
8
- 4 Have you considered Unicode characters as well? – thefourtheye Commented Jan 21, 2016 at 16:29
- Do you mean special characters or only letters? – Javier Conde Commented Jan 21, 2016 at 16:31
- Possible duplicate of How to randomize (shuffle) a JavaScript array? – Oriol Commented Jan 21, 2016 at 16:35
- get all the possible characters Do you even know how many there are in Unicode? – Derek 朕會功夫 Commented Jan 21, 2016 at 16:38
- Why do you need it for all characters? – MinusFour Commented Jan 21, 2016 at 16:42
2 Answers
Reset to default 8Here 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 remendation:
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", "{", "|", "}", "~"]
Here is a one liner for all lowercase chars:
Array(26)
.fill(97)
.map((x, y) => String.fromCharCode(x + y))