My array contains a blank space [" "]. When I .join the space with underscores, the space element in the resulting string is not visible in the html

Viewed 1027

When displayed in the console, the result I get between the p tags contains the space in index 3, which is correct.

But when displayed on page I get "_ _ _ _". The space in index 3 is not visible. Here's the CodePen.

How can I get the space between the underscores to be displayed on the page? I CANT EVEN GET THE SPACE TO DISPLAY ON HERE! It shows up like this "_ _ _ _". There should be a space between underscore 2 and 3!

Thank you very much!

.toString instead of .join makes no difference.

.textContent instead of .innerHTML also makes no difference.

<html>
  <p id="myid"></p>

  <script>
    var myArray = ["_", "_", " ", "_", "_"];
    var hiddenWord = document.getElementById('myid');
    var temp;

    function newGame() {
      temp = myArray.join(" ");
      hiddenWord.innerHTML = temp;
    }

    newGame();
    console.log("temp variable", temp);
    console.log(myArray);
  </script>
</html>
4 Answers

When the HTML is rendered, normally sequences of white space are collapsed to a single white space. Use white-space: pre; on the element to preserve the Sequences of white spaces:

var myArray = ["_", "_", " ", "_", "_"];
var hiddenWord = document.getElementById('myid');
var temp;

function newGame() {
  temp = myArray.join(" ");
  hiddenWord.innerHTML = temp;
}

newGame();
#myid {
  white-space: pre;
}
<p id="myid"></p>

Many spaces are in HTML rendered as a single space, as all other whitespace. To overcome this problem, you could use a nonbreaking space &nbsp;, which gives the wanted space.

function newGame() {
    temp = myArray.join(" ").replace(/\s/g, '&nbsp;');
    hiddenWord.innerHTML = temp;
 }

var myArray = ["_", "_"," ","_","_"],
    hiddenWord = document.getElementById('myid'),
    temp;

newGame();
console.log("temp variable", temp);
console.log(myArray);
<p id="myid"></p>

Instead of joining using space(' '), Use nbsp of html

temp = myArray.join("&nbsp;");

this happens because html does not take in account two spaces you can think of it as a trimed string in javascript

Related