Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>
like image 478
Ryan Rodriguez Avatar asked Jun 15 '19 08:06

Ryan Rodriguez


1 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>
like image 155
Ori Drori Avatar answered Oct 01 '22 08:10

Ori Drori