Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
95
rated 0 times [  97] [ 2]  / answers: 1 / hits: 23412  / 12 Years ago, sun, may 6, 2012, 12:00:00

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.


More From » dom

 Answers
45

White space characters are usually collapsed in HTML (by default).



You can replace it with the &nbsp; entity:



var text = text.replace(/s/g, '&nbsp;');


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:




  • Put the text in a pre element.

  • Set the CSS 2 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.


[#85744] Saturday, May 5, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mariann

Total Points: 201
Total Questions: 133
Total Answers: 107

Location: Czech Republic
Member since Thu, Aug 11, 2022
2 Years ago
;