Reputation: 82297
When adding in text with small whitespace appended to it for alignment purposes the whitespace is trimmed off (the whitespace is added in c# so by the time it gets to front end Javascript it cannot be edited - it would be nice to just use some CSS to do this but it is not an option).
Here is what I tried so far:
var zlp = document.getElementById("testDiv")
zlp.innerHTML = "hello hello"
var zzz = document.createTextNode("hello hello")
zlp.appendChild(zzz)
<div id="testDiv"></div>
Both of which produce hello hello
.
Upvotes: 12
Views: 26394
Reputation: 1078
use a html tag 'pre'
Example:
<pre>
A line
A line with indent
</pre>
result:
A line A line with indent
Upvotes: 1
Reputation: 15024
use
zlp.innerHTML = "hello hello";
Like everyone else just said.
Upvotes: 1
Reputation: 816600
White space characters are usually collapsed in HTML (by default).
You can replace it with the
entity:
var text = text.replace(/\s/g, ' ');
\s
will match any white space character, such as space, tab and new line. If you only want to replace space, use / /g
instead.
Other options which avoid string manipulation:
pre
element.white-space
property to pre
as @Esailija pointed out. You can always add CSS properties dynamically to elements, they don't have to be specified in a style sheet.Upvotes: 29
Reputation: 3381
White space is collapsed in HTML. It's not a JS issue, the same would happen if you typed that manually in the HTML document. You need to replace the spaces with
zlp.innerHTML = "hello hello".replace( / /g, " " );
Upvotes: 1