2

How to make string "Review 1" with sequencial white spaces in the middle to be rendered as such. Please see the example below.

<div id="target"></div>​

var name = "Review     1"
$('#target').html(name);​

Thanks

eomeroff
  • 9,599
  • 30
  • 97
  • 138

8 Answers8

7

Use one &nbsp; for every space

Curtis
  • 101,612
  • 66
  • 270
  • 352
Anders Lindén
  • 6,839
  • 11
  • 56
  • 109
  • 2
    or replace .html() by .text() – redwind Dec 19 '12 at 10:32
  • 1
    @redwind why? That doesn't make any difference to how white-space is rendered – Esailija Dec 19 '12 at 10:35
  • sorry,it's my mistake, .text() can render space without using   but only once space. if you want to render multi spaces you need use   instead. – redwind Dec 19 '12 at 10:50
  • @redwind `.text()` or `.html()` has nothing to do with rendering but how the input is interpreted. With `.text()`, `"hi"` would literally make that text, with `.html()` you end up with a span element. If you use `.text()` for ` `, then you literally get that text, if you interpret it as html, you get a [U+00A0 NO-BREAK SPACE](http://www.fileformat.info/info/unicode/char/a0/index.htm) character. – Esailija Dec 19 '12 at 15:42
  • @Esailija: cause in this case, SonOfOmer want to insert a text into a div, it's not content any html tag, so i suggest him use text(). I tested it on my browser i relized that text() function can render only once space. sorry,i'm not good at EngLish, so, quite difficult for me to explain clearly. – redwind Dec 20 '12 at 09:34
7

Change how white-space is handled:

<div id="target" style="white-space: pre;"></div>​

http://jsfiddle.net/PHvVh/1/

Esailija
  • 138,174
  • 23
  • 272
  • 326
1

If you need multiple spaces you can use the html encoded character for a space: &nbsp; (=non break space)

var name = "Review&nbsp;&nbsp;&nbsp;&nbsp;1"
Chris Laarman
  • 1,559
  • 12
  • 25
1
var name = "Review     1".replace(/ /g, "&nbsp;");

$('#target').html( name );​
Andreas Louv
  • 46,145
  • 13
  • 104
  • 123
1

You need to use .replace() Give this a try:

$(function () {
    var name = "Review     1"
    $('#target').html(name.replace(/\s/g, '&nbsp;'));
});​

Working example: http://jsfiddle.net/t4jtJ/1/

PhearOfRayne
  • 4,990
  • 3
  • 31
  • 44
0

Use &nbsp; like others have said. If the text is dynamic, use replace:

name = name.replace(/\s/g,'&nbsp;');
Tetaxa
  • 4,375
  • 1
  • 19
  • 25
0
var name = "Review     1"
name.split(' ').join('&nbsp');
$('#target').html(name);​
0

Well you can use <pre> tag:

$('#target').html('<pre>'+name+'</pre>');

checkout the fiddle: http://jsfiddle.net/8BJuB/

Jai
  • 74,255
  • 12
  • 74
  • 103