繁体   English   中英

如何在Javascript中的字符串末尾添加空格

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

我正在编写一个程序,根据用户输入创建一个倾斜的d。 程序询问行数并相应地产生输出。 如果用户输入5,则应产生以下输出:

d
 d
  d
   d

我的实际输出是:

d
d
d
d

这是我的Javascript代码:

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;                                                                                                   
    }

}

当我将空格变量字符串从''替换为' - '时,它似乎与输出:

d
-d
--d
---d

我不知道我需要改变什么来获得上面的输出但是用空格而不是破折号。

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>

代替空格使用html代码&nbsp; 您的代码将开始工作,因为默认情况下,无论您提供多少,浏览器都只接受一个空格。 例:

space = '&nbsp;'; 

默认情况下,浏览器会将所有空间“折叠”到一个空格中。

一种解决方案是使用<pre>元素代替输出。 像这样:

<pre type="text" id="outputNumber1"></pre>

<pre>显示预格式化的文本。 因此显示输出,保留所有空格和换行符。

如果您不想更改元素类型,可以在元素中添加CSS声明white-space:pre以获得与上面相同的结果。 像这样:

<output type="text" id="outputNumber1" style="white-space:pre;"></output>

或者您可以在<style>块中单独设置它,如下所示:

<style>
    body{background-color: green;} 
    #outputNumber1{white-space:pre;}
</style>

您可以在html语言中使用&nbsp代表不间断空格。

使用nbsp此添加非打破空间到你的HTML。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM