Skip to content Skip to sidebar Skip to footer

String That Contains All Ascii Characters

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

Solution 1:

var s = ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~';

Solution 2:

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.

Solution 3:

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

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

Solution 4:

Just wanted to put this here for reference. (takes about 13/100 to 26/100 of a ms on my computer to generate).

var allAsciiPrintables = JSON.stringify((Array.from(Array(126 + 32).keys()).slice(32).map((item) => {
    returnString.fromCharCode(item);
})).join(''));

Decomposed:

var allAsciiPrintables = (function() {
    /* ArrayIterator */var result = Array(126 + 32).keys();    
    /* [0, 126 + 32] */
    result = Array.from(result);
    /* [32, 126 + 32] */
    result = result.slice(32);
    /* transform each item from Number to its ASCII as String. */
    result = result.map((item) => {
        returnString.fromCharCode(item);
    });
    /* convert from array of each string[1] to a single string */
    result = result.join('');

    /* create an escaped string so you can replace this code with the string 
       to avoid having to calculate this on each time the program runs */
    result = JSON.stringify(result);

    /* return the string */return result;
})();

The most efficient solution(if you do want to generate the whole set each time the script runs, is probably)(takes around 3/100-35/100 of a millisecond on my computer to generate).

var allAsciiPrintables = (() => {
    var result = newArray(126-32);
    for (var i = 32; i <= 126; ++i) {
        result[i - 32] = (String.fromCharCode(i));        
    }
    returnJSON.stringify(result.join(''));
})();

strangely, this is only 3-10 times slower than assigning the string literal directly(with backticks to tell javascript to avoid most backslash parsing).

var x;
var t;

t = performance.now();
x = '!\"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~';
t = performance.now() - t;
console.log(t);

.

Solution 5:

Without doing several appends:

var s = Array.apply(null, Array(127-32))
  .map(function(x,i) {
    returnString.fromCharCode(i+32);
  }).join("");
  document.write(s);

Post a Comment for "String That Contains All Ascii Characters"