I have an array ["hello", "there", "buddy"] and I want to join these strings together. The issue is that I want to join them together with multiple white-spaces, specifically three of them. My code runs as
sentence = sentence.join(" ")
However, instead of returning
hello there buddy
it returns as
hello there buddy
How do I fix this?
The problem is that browsers collapse whitespace runs between words. You can see this, and counter it, a couple ways.
displays with multiple spaces here on Stack Overflow, and consequently your browser, because I told it to use code formatting. I can do it also with:
which tells the browser to display using
<pre>formatting, which, again, is a fixed-width font which respects the whitespaces.If you don’t use a fixed-width format designed to preserve whitespace, you have to get tricky.
In HTML you can use a non-breaking space:
1 2 3
which, in HTML looks like:
If I’d used regular whitespace it would look like:
1 2 3
There are CSS games that can be played too, but using
is probably the most common.To try this at home, save the following to a file called “test.html” and open it with your browser: