Categories
JavaScript Answers

How to create a string that contains all ASCII characters with JavaScript?

Spread the love

Sometimes, we want to create a string that contains all ASCII characters with JavaScript.

In this article, we’ll look at how to create a string that contains all ASCII characters with JavaScript.

How to create a string that contains all ASCII characters with JavaScript?

To create a string that contains all ASCII characters with JavaScript, we can use the String.fromCharCode method to get the characters with codes from 32 to 126 and combine them together.

For instance, we write:

let s = '';

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

console.log(s)

We create a for loop that looped from 32 to 126, assign them to i, and call String.fromCharCode with i.

Then we concatenate the returned character to s.

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

Conclusion

To create a string that contains all ASCII characters with JavaScript, we can use the String.fromCharCode method to get the characters with codes from 32 to 126 and combine them together.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *