How to insert white spaces - Javascript

Asked

Viewed 7,418 times

4

I am doing some exercises and one of them asks me to create a code that reproduces an "ASCII art", I read about and saw that it was a special character and I tried to insert the space in its Unicode form " s", "u0020", but without success. I saw some people talking about using regular expressions. I thank you already

<script>
document.write("XXXXX<br>");
for (var i =0;i<2;i++){
document.write("X   X<br>")
};
document.write("XXXXX<br>");
</script>


                      XXXXX
                      X   X
                      X   X   
                      XXXXX

1 answer

6


The problem of space, even using the HTML entity &nbsp;, is the rendering of characters. In proportional fonts, each character occupies a different space according to its width (width). In sources called monospaced (single space) any character occupies the same space, such as, for example, the source Consoles, widely used in programming and, even, is the standard source of this response editor, as shown in the print below:

inserir a descrição da imagem aqui

See that all the fonts listed above are monospaced.

Example of the source Consoles:

inserir a descrição da imagem aqui

So you have two options:

1. Tag <pre>

The tag <pre> shows the text as it is, already converting the font type to monospace:

<pre>
<script>
document.write("XXXXX<br>");
for (var i =0;i<2;i++){
document.write("X   X<br>")
};
document.write("XXXXX<br>");
</script>
</pre>

2. Use the entity &nbsp;:

In this case you need to use a font monospace:

body{
   font-family: consolas;
}
<script>
document.write("XXXXX<br>");
for (var i =0;i<2;i++){
document.write("X&nbsp;&nbsp;&nbsp;X<br>")
};
document.write("XXXXX<br>");
</script>

  • Thanks Sam, I used the <pre> tag and worked!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.