two types of newlines (\n and \r\n) and browser

H

HopfZ

Not a question.

I tested how two kinds of newlines (\n and \r\n) interact with three
browsers: Fx (Firefox 2), Op (Opera 9), Ie (IE 7) (all three on Windows
XP).

Result:

The string 'A\nB\r\nC' contains both forms of newlines.

var s1 = 'A\nB\r\nC';
document.getElementById('textarea_id').value = s1;
Above code will put that string to a textarea. In all three browsers,
the textarea will then look like:
-----
|A |
|B |
|C |
-----

Then let's do this:
var s2 = document.getElementById('textarea_id').value;
Now, in all three browsers, s2 is not the same as s1.
In Fx, we have s2 == 'A\nB\nC'. In Op and Ie, we have s2 ==
'A\r\nB\r\nC'.

Suppose we have the following html code.
<textarea id="foo">A
B
C</textarea>
<textarea id="bar"></textarea>

Open it in browser and type A, Enter, B, Enter and C in the textarea
with id "bar" and click a button which does:
s3 = document.getElementById('foo').value;
s4 = document.getElementById('bar').value;

Now, in Fx, s2 == s3 == s4 == 'A\nB\nC'. In Op and Ie, s2 == s3 == s4
== 'A\r\nB\r\nC'.

In most cases, it's not needed to care about two kinds of newlines. But
in some cases, it is.

Suppose we want to take text from a textarea and count the number of
letters in each line and show the numbers.
For example, If I fill the textarea as below:
-----------------
|My name is |
|Hiro Nakamura. |
|I have a message.|
-----------------
, the result should be:
-----------------
|10 |
|14 |
|17 |
-----------------

The corresponding javascript should be:

function lines2Numbers(s){
var li = s.split('\n');
for(var i=0;i<li.length;i++){ li = li.length };
return li.join('\n');
}

button1.onclick = function(){
var i = document.getElementById('input');
var o = document.getElementById('output');
// o.value = lines2Numbers(i.value); No.
o.value = lines2Numbers(i.value.replace(/\r\n/g,'\n')); // Yes.
}

Thanks.
 
J

John G Harris

Not a question.

I tested how two kinds of newlines (\n and \r\n) interact with three
browsers: Fx (Firefox 2), Op (Opera 9), Ie (IE 7) (all three on Windows
XP).
<snip>

HTML allows three kinds of line terminators : CR, LF, and CRLF. In
javascript these are \r, \n, and \r\n.

I'm not surprised that text held in a DOM object uses whatever line
terminator is convenient for the browser.

John
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top