Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a space at the end of a string in Javascript

I am writing a program which creates a slanted d based off of user input. The program asks for the number of rows and produces the output accordingly. If the user enters in 5 it should produce an output of:

d
 d
  d
   d

My actual output is:

d
d
d
d

Here is my Javascript code:

spaceArray = []; 
space = ' '; 
spaceMain = ' ';


function processingFunction(rows){ //passes the input as variable rows
    var spaceCounter = 0;          
    var counter = 0;               

    while (counter<rows){    
        while (spaceCounter<counter){ 
            spaceMain = spaceMain + space;  //adds a space before the d
            spaceCounter++;         
        }
        counter++; 
        spaceCounter=0; 
        spaceArray.push(spaceMain);  //adds spaceMain to the end of spaceArray
        spaceMain = ' '; 
    }

    for (i = 0; i<rows; i++){
        d = spaceArray[i]+"d<br>";
        document.getElementById("outputNumber1").innerHTML += d;                                                                                                   
    }

}

When I replace the space variable string from ' ' to '-' it seems to work with an output of:

d
-d
--d
---d

I am not sure what I need to change to get the above output but with spaces instead of dashes.

HTML:

<!DOCTYPE>
<html>
<head>
</head>
<style>
    body{background-color: green;} 

</style>

<body>
    <center><h2>Slanted d</h2></center>
    <h3>Input the number of rows you would like your slanted d to be in the input text box</h3>
    <input type="text" id="inputNumber"></input> 
    <button type="button" onclick="processingFunction(document.getElementById('inputNumber').value)">Create slanted d</button> 
    <br><br>
    <output type="text" id="outputNumber1"></output>

<script src="slantedDJS.js"></script>

</body>
</html>
like image 696
Tomasz Dobrowolski Avatar asked Dec 11 '22 12:12

Tomasz Dobrowolski


1 Answers

In place of spaces use the html code &nbsp; your code will start working, because by default the browser accepts only a single space no matter how many you give. Example:

space = '&nbsp;'; 
like image 61
Shakti Phartiyal Avatar answered Dec 21 '22 23:12

Shakti Phartiyal