javascript JS中单词之间的空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12304713/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 15:52:54  来源:igfitidea点击:

space between words in JS

javascripthtmlpopupspace

提问by Nave Tseva

I have this JS code:

我有这个JS代码:

function myPopUp()
{
    var y;
    var name=prompt("Please enter your name"," ???? ?? ???");
    if (name!=null)
    {
        y= '  How are you today?';
        document.getElementById("popup").innerHTML = y;
        var x="";
        var time=new Date().getHours();
        if (time<20)
        {
            x="Have a nice day" +  name + '!';
        }
        else
        {
            x='   Great evening  '+ name +'   !  ';
        }
        document.getElementById("demo").innerText = x ;
    }
}

with this HTML code:

使用此 HTML 代码:

<body>
    <button onclick="myPopUp()" >??? ???</button>
    <p id="demo"></p>
    <p id="popup"></p>
</body>

My question: When someone write their name there is no space between the words? How do I put a space between words in JS?

我的问题:当有人写他们的名字时,单词之间没有空格?如何在JS中的单词之间放置空格?

Thank you.

谢谢你。

回答by Jeremy J Starcher

In HTML, extra white space is collapsed to a single space (ASCII 32) character.

在 HTML 中,多余的空白被折叠为单个空格 (ASCII 32) 字符。

If you MUST force a space, use the html identity &nbsp;which is a non-breaking space.

如果您必须强制使用空格,请使用&nbsp;不间断空格的 html 标识。

Better yet, use CSS to put margins around your element and make the spacing visual.

更好的是,使用 CSS 在元素周围放置边距并使间距可视化。

回答by Jeff

Looks like you just need a space after "day," so try this:

看起来你只需要在“一天”之后一个空格,所以试试这个:

x="Have a nice day " +  name + '!';