简体   繁体   English

如果单词之间有多个空格,HTML会在字符串中剥离空格

[英]Html is stripping empty space in string if there is more than one space between words

I am trying to display a string like this on the html page 我正在尝试在html页面上显示这样的字符串

"Hello.    Hello"

When i pass the data from ajax to html, its displaying it as "Hello. Hello" even though i pass it in the following way: 当我将数据从ajax传递到html时,即使我通过以下方式将其显示为“ Hello。Hello”:

$("#tag").text("Hello.     Hello");

In html i have the div as defined below 在HTML中,我有如下定义的股利

<div id="tag"></div>

Give your desired destination, in this case #tag , white-space: pre; 给出您想要的目的地,在这种情况下为#tagwhite-space: pre; in CSS. 在CSS中。 This will fix it (See snippet) 这将解决问题(请参见代码段)

 $("#tag").text("Hello. Hello"); 
 #tag { white-space: pre; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id = "tag"></div> 

使用pre元素

$("#tag").append("<pre>Hello.     Hello</pre>");

HTML automatically removes whitespace, you can prevent this by using &nbsp; HTML会自动删除空格,您可以使用&nbsp;来防止这种情况&nbsp; instead of a space. 而不是空间。 Read more on the non-breaking space here . 这里阅读更多关于不间断空间的信息

 var html = "Hello.&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;World."; $("#tag").html(html); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="tag"></div> 

If you want this to work without replacing the spaces yourself, you can also use a RegExp to do this for you: 如果您希望此方法在不自己替换空格的情况下起作用,则还可以使用RegExp为您执行此操作:

 var html = "Hello. World."; let re = / /g; $("#tag").html(html.replace(re, "&nbsp;")); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="tag"></div> 

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

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