Kumar
Kumar

Reputation: 741

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

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

Upvotes: 0

Views: 410

Answers (3)

Luca Kiebel
Luca Kiebel

Reputation: 10096

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>

Upvotes: 1

sid-m
sid-m

Reputation: 1554

use the pre element

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

Upvotes: 3

Thomas van Broekhoven
Thomas van Broekhoven

Reputation: 898

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>

Upvotes: 4

Related Questions