\n or \r\n (or even \r) in other words. I’m keen to avoid sniffing the user agent string.
First attempt:
var osLineBreak = (function () {
var p = document.createElement('p');
p.innerHTML = '<br>';
return p.innerText;
}());
Unfortunately Firefox does not provide innerText, and textContent returns the empty string in this case.
Second attempt:
var osLineBreak = (function () {
var
lineBreak,
body = document.body,
range = document.createRange(),
selection = window.getSelection(),
p = document.createElement('p');
// we cannot make a selection unless `p` is in the DOM,
// so ensure that it is not visible when we insert it
p.style.position = 'absolute';
p.style.left = '-9999px';
// Firefox returns the empty string if `innerHTML` is
// set to "<br>", so include leading and trailing
// characters
p.innerHTML = '%<br>%';
body.appendChild(p);
// wrap `p` in `range`
range.selectNodeContents(p);
// make a selection from `range`
selection.addRange(range);
// see how the line break is treated in the selection
// (provide a sane fallback in case we get the empty string)
lineBreak = /%(.*)%/.exec(selection.toString())[1] || '\n';
// revert our fiddlings
selection.removeAllRanges();
body.removeChild(p);
return lineBreak;
}());
Is there a less convoluted technique that I’ve overlooked?
Update in 2015: As you can see from the below, even back in 2011 Chrome and Firefox were using
\non all platforms. Opera and IE used\r\non Windows. Since then, Opera has switched to WebKit like Chrome, and so presumably uses\n. IE8 was the last IE that used\r\nin textareas; from IE9 onward, IE also uses just\n. Haven’t tested mobile browsers.Coming rather late to the party, but if you really want to know what line separator character the browser is using in
textareas and such (which can vary within browser even on the same OS), you can find out with a sneaky trick:This works because the browsers that use
\r\nconvert the\non-the-fly when parsing the HTML string. Here’s a live running copy you can try for yourself with your favorite browser(s). In IE and Opera (even Opera running on *nix), you’ll find it’s\r\n. On Chrome, Firefox, and Safari (even running on Windows), you’ll find it’s\n.That said, my experience is that inserting
\n(e.g., when assigning to thevalueproperty, as opposed to the HTML string bit above) works even on browsers that would normally use\r\n. But that doesn’t mean there aren’t edge cases, and I have to admit I don’t do that (insert line breaks intextareas) with any kind of regularity, so if there are issues and I really should be using\r\non some browsers, I may just have not found them.