7

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.

Programmer
  • 365
  • 2
  • 9
magician11
  • 4,234
  • 6
  • 24
  • 39

2 Answers2

10

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.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
2

You can do this:

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

Because maximum hex is 65536.

Maximum hex: 16 ^ 4

Programmer
  • 365
  • 2
  • 9