How to preserve whitespace in dynamically added javascript DOM element without using CSS?

前端 未结 4 1570
傲寒
傲寒 2020-12-20 18:06

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

4条回答
  •  不思量自难忘°
    2020-12-20 18:32

    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:

    • 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.

提交回复
热议问题