Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a random character from a range in JavaScript?

Looking at Katakana characters (http://en.wikipedia.org/wiki/Katakana#Unicode) how would I get a random character from a Unicode range?

I'm close with

String.fromCharCode(0x30A0 + Math.random() * 60);

The '60' is kind of a rough guess of the range. Is there a way to code in "U+30A0 ... U+30FF" ?

Thanks.

like image 460
magician11 Avatar asked Oct 18 '13 11:10

magician11


2 Answers

You can do this :

String.fromCharCode(0x30A0 + Math.random() * (0x30FF-0x30A0+1));

Note that 0x30FF-0x30A0 is 95, and if you want the last one you must add 1 (Math.random returns a result in [0,1[), which makes 96, not 60.

like image 145
Denys Séguret Avatar answered Sep 21 '22 11:09

Denys Séguret


You can do this:

String.fromCharCode(Math.floor(Math.random() * 65535));

Because maximum hex is 65536.

Maximum hex: 16 ^ 4

like image 23
Programmer Avatar answered Sep 24 '22 11:09

Programmer