3

I am entering some text in a input box. When entering a text I am giving some spaces means more then 1 space just say 4 or 5. But when I get the value from the input box and append to a div. It replaces all extra spaces with once single space.

Example, I enter text like this. "Hi     can   you please look    on   it      ?"

then if get the value using $("#inpuboxid").val(); then append that value to div.

it become like this: "Hi can you please look on it ?"

How to achieve this, as browser automatically replaces extra spaces with once space

Cœur
  • 37,241
  • 25
  • 195
  • 267
Bora
  • 1,933
  • 3
  • 28
  • 54

2 Answers2

6

HTML squishes adjacent spaces together by default. Add a style of "white-space: pre;" to your div. This should keep all the white space in its contents.

<div style="white-space: pre;">Hi    can  you please look    on  it     ?</div>

See this Fiddle

Zword
  • 6,605
  • 3
  • 27
  • 52
Anthony Chu
  • 37,170
  • 10
  • 81
  • 71
1

After you set the text of the element, you can use the html method to replace spaces with &nbsp;. Here is an example.

$("#somelement").text($("#inpuboxid").val()).html(function(index,html){return html.replace(/ /g, '&nbsp;');})
Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171