-1

I have a variable in JavaScript that contains the contents of an html textarea. When I print the variable all that were entered by the user are forgotten. Is there any way to find the spaces in the string so I can separate each line?

Oded
  • 489,969
  • 99
  • 883
  • 1,009
Alex
  • 1,060
  • 2
  • 17
  • 35

3 Answers3

1

here is a function , you can use for your script:

function nl2br (str) {
 var breakTag = ''; return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2'); 
}
elo
  • 615
  • 4
  • 11
0

HTML collapses adjacent whitespace - so if you are displaying within HTML, that's what you are seeing.

You can replace spaces with non break spaces:   - this will ensure they are displayed in HTML and not collapsed.

Another option is to place them in a <pre> element

Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • Thanks, I have a better understanding of how HTML treats user input now but I should have been more specific about what I'm needing to do... It is important that I know where the user has entered a new line in the textarea. Is there any way of locating the spaces in the JavaScript variable? – Alex Feb 04 '12 at 14:56
  • @Alex - And what _do_ you need to do? – Oded Feb 04 '12 at 14:57
0

You mean all newlines? HTML ignores newlines and collapses whitespace by default. Print them inside a <pre> tag, or check out the CSS white-space property: http://www.w3schools.com/cssref/pr_text_white-space.asp

You can also replace newlines with <br> tags using:

while (str.indexOf("\n") > -1) str = str.replace("\n","<br>");
avramov
  • 2,119
  • 2
  • 18
  • 41
  • thanks, the JavaScript variable already contained the spaces, the HTML was just removing them when I was printing it. – Alex Feb 04 '12 at 15:13