PDA

View Full Version : linebreaks in innerHTML


ubik
03-01-2006, 10:51 PM
Hello I have noticed that when using innerHTML you cannot put line breaks in the code, I am wondering if there is anyway around this.. for example how could i get this to work?


function replace() {
box = document.getElementById('csscontainer');
box.innerHTML = '$textfile';
}


the $textfile is a php variable that has a document of text in it with many line breaks or you can look at it like this:


function replace() {
box = document.getElementById('csscontainer');
box.innerHTML = 'some text goes here
some text goes here some text goes here
some text goes here, some text some text
goes here some text goes heresome text goes here';
}


? would i have to edit each text file? or could i do this with the script? i know i could use something like indexOf to find spaces between words.. but is there something to find the line breaks of a string? or are line breaks within strings not allowed in javascript?

gph
03-01-2006, 11:02 PM
something like:

var str='$textfile';
box.innerHTML = str.replace(/\n/g,'<br>');

liorean
03-01-2006, 11:10 PM
Line breaks are not allowed to appear literally in strings. They may appear as '\n' if your intent is to represent a line feed character. Escaped line breaks may appear in strings for source formatting purposes, but they are removed from the parsed string. And finally, if you want an HTML line break, you can use the br element or if it makes sense wrap the text in any other element that causes a line break afterwards.var
a="texttext",
b="text\ntext",
c="text\
text";

alert(a); // => "texttext"
alert(b); // => "text
// text"
alert(c); // => "texttext"

glenngv
03-02-2006, 09:26 AM
In PHP, replace all newlines in the $textfile variable with <br /> before embedding it as the innerHTML value. I don't know PHP so I can't post any code. Just remember that the final output should be like this:
box.innerHTML = 'some text goes here<br />some text goes here some text goes here<br />some text goes here, some text some text<br />goes here some text goes heresome text goes here';

Beagle
03-02-2006, 05:44 PM
Head to PHP.net and check out the string library of functions, specifically str_replace (http://us3.php.net/manual/en/function.str-replace.php). As has been said above, you want to replace "\n" with either nothing at all, or <br /> if you want to keep the line breaking.

gph's suggestion won't work because the javascript engine is choking on the line-breaks during the evaluation of the php generated text. It must be done on the server side.

Also, you might want to escape singe-quotes in the text file as well, or your javascript will choke on those too because you're using single-quotes to wrap your string value. If you were using double quotes, you'd want to escape double quotes.

GJay
03-02-2006, 06:36 PM
nl2br($string) is a native php function that does exactly what itsays :)

Beagle
03-02-2006, 06:46 PM
zing!:thumbsup: