0

I am trying to display a string like this on the html page

"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:

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

In html i have the div as defined below

<div id="tag"></div>
Preview
  • 35,317
  • 10
  • 92
  • 112
Kumar
  • 731
  • 2
  • 12
  • 19
  • 1
    has an answer at http://stackoverflow.com/questions/1981349/regex-to-replace-multiple-spaces-with-a-single-space#1981366 – sid-m May 20 '17 at 16:24
  • @sid-m i dont want to remove the spaces if there are more than one space, i want to show it on the ui the same way. – Kumar May 20 '17 at 16:25
  • 2
    then you can use the `pre` element – sid-m May 20 '17 at 16:26

3 Answers3

4

Give your desired destination, in this case #tag, white-space: pre; in 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>
3

use the pre element

$("#tag").append("<pre>Hello.     Hello</pre>");
sid-m
  • 1,504
  • 11
  • 19
1

HTML automatically removes whitespace, you can prevent this by using &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:

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>
Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44