views:

73

answers:

2

I'm trying to parse some text into a textarea control and at the same time replace all
with ordinary line break chars.

I have been able to do it in windows by replacing
with CR (it didn't work with CRLF strangely enough, it gave me linebreak + empty space) but I'm afraid that this code won't work in Unix/Mac because they use LF for line break.

Is there any way to use the system default line break char in javascript? Something similar to Environment.NewLine in .Net

(I wasn't able to write backslash in this editor but I use \r for CR and \n for LF)

Edit: I should probably mention that everything works with FF, it's as always internet explorer (8) I'm having problems with.

Edit2:

I can reproduce my problem with this code. When I run it in IE8 I get "row1 row2" but when I run it in FF I get real line breaks:


<html>
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"&gt;&lt;/script&gt;
    <script type="text/javascript">

    function fill() {
        var text = "row1<br /><br />row2";

        $('#fill_me').text(text.replace(/<br \/>/g, '\n'));
    }

    </script>

</head>

<body onload="fill()">
    <textarea rows=10 cols=100 id="fill_me"></textarea>
</body>
</html>

+1  A: 

You can always use \n as your linebreak character in Javascript.

For example the statement,

document.getElementById('mytextarea').value = "This is some text.\n\nAnd here is some more.";

adds two returns between the "This is some text." and "And here is some more." in IE, Firefox, Chrome, Safari, etc.

Robusto
I tried that but it only gave me empty spaces..
Irro
I'm using (with jQuery): $('#text_field').text(data.replace(/<br \/>/g, '\n'));
Irro
@Irro: I'd love to see how you tried it then, because it works on all the browsers I have at my disposal. You did say you were putting the value into a `<textarea>`, did you not?
Robusto
I added a small example in my original post that reproduce my problem.
Irro
+1  A: 

Your problem isn't the newline character, its your use of jQuery functions.

You should be using .val() instead of .text() for changing the value of a <textarea>. .text() is for changing the textContent of nodes (like a <div>, etc). Newline chars inside of text() will likely be converted to plain spaces...

Demonstrated on jsfiddle

gnarf
Oh man, I'm so mad at myself for missing that one :). Thanks!
Irro