views:

229

answers:

3

Hi,

I want to create a string in JavaScript that contains all ascii characters. How can I do this?

A: 

Python 2.6+:

import json
print json.dumps(''.join(chr(x) for x in range(32, 127)))
Ignacio Vazquez-Abrams
What's that got to do with Javascript?
cletus
It generates a string that can be copied and pasted right into a .js file. Generating the actual string in JavaScript code is a waste of time.
Ignacio Vazquez-Abrams
Regardless of it's a waste of time, it was the question.
Ben S
Jejejejejejejeje
Kiewic
+3  A: 

My javascript is a bit rusty, but something like this:

s = '';
for( var i = 32; i <= 126; i++ )
{
    s += String.fromCharCode( i );
}

Not sure if the range is correct though.

Edit:
Seems it should be 32 to 127 then. Adjusted.

Edit 2:
Since char 127 isn't a printable character either, we'll have to narrow it down to 32 <= c <= 126, in stead of 32 <= c <= 127.

fireeyedboy
He did specify ASCII, and likely wants only printable characters, so you'll want to stick to 32 <= c <= 127.
Michael Petrotta
Actually, character 127 isn't really printable, so 32 <= c < 127.
Ignacio Vazquez-Abrams
You are right Michael, I wasn't sure about the actual range of ASCII. Shame on me. :-/ But I've looked it up now, and it seems we should narrow it down to 32 to 126, since DEL is not a printable character either I believe. But correct me if I'm wrong.
fireeyedboy
@Ignacio: Well, there you go, you beat me to it.
fireeyedboy
I need all ascii chatacters. However, this helps, too. Thanks
Gjorgji
@Gjorgji: which characters are you missing? Why do you think that those are not all?
Joachim Sauer
@Joachim: I'll bet he's looking for "all printable Western European characters" or "all printable characters in my native script". The definition of the word "ascii", especially when rendered in lowercase, has gotten a bit sloppy over the years, I've noticed.
Michael Petrotta
+2  A: 

Just loop the character codes and convert each to a character:

var s = '';
for (var i=32; i<=127;i++) s += String.fromCharCode(i);
Guffa