0

\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?

davidchambers
  • 23,918
  • 16
  • 76
  • 105
  • 3
    just curious as to why it would matter? – jcomeau_ictx May 27 '11 at 06:02
  • Note that the string assigned to the *textContent* or *innerText* property is not parsed, it is treated as literal text. Further, [*innerText*](http://msdn.microsoft.com/en-us/library/ms533897%28v=VS.85%29.aspx) is a proprietary Microsoft extension (there is no standard) and not supported by all browsers. *textContent* is a [W3C DOM 3 Core](http://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-textContent) property that isn't supported by all browsers either, but most support one or the other, some both. – RobG May 27 '11 at 06:14
  • @jcomeau_ictx Good question. I'm working on an enhancement to [Hashify Editor](https://bitbucket.org/davidchambers/hashify-editor). When the user hits _enter_ the appropriate combination of leading spaces and/or tabs should be inserted. Most editors do this (or a more intelligent version of it) and it's particularly useful when writing code snippets. Since Markdown requires code snippets to be indented by four spaces, one ends up typing five keystrokes between one line of code and the next. – davidchambers May 27 '11 at 06:36
  • Hmm. Too bad java is often disabled these days. A simple java 1.1 applet that does `System.getProperty("line.separator")` would do it. – Mike Samuel May 27 '11 at 06:47
  • I'd love someone to tell me that such a thing is accessible via JavaScript, too. In fact a Firefox-specific property would be fine, since the `innerText` approach works in other browsers. – davidchambers May 27 '11 at 07:11

3 Answers3

5

Update in 2015: As you can see from the below, even back in 2011 Chrome and Firefox were using \n on all platforms. Opera and IE used \r\n on Windows. Since then, Opera has switched to WebKit like Chrome, and so presumably uses \n. IE8 was the last IE that used \r\n in 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:

function getLineBreakSequence() {
    var div, ta, text;

    div = document.createElement("div");
    div.innerHTML = "<textarea>one\ntwo</textarea>";
    ta = div.firstChild;
    text = ta.value;
    return text.indexOf("\r") >= 0 ? "\r\n" : "\n";
}

This works because the browsers that use \r\n convert the \n on-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 the value property, 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 in textareas) with any kind of regularity, so if there are issues and I really should be using \r\n on some browsers, I may just have not found them.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

On a webpage, the flavor of linebreak does not matter in the OS. Linebreaks are not taken in account when diplayed on a webpage. You need a BR element or block element to do that, and those are cross-platform and supported on all browsers.

See this page for a simplistic explanation.

UPDATE:

So the need if for formatting textbox, and there line breaks are important. Sorry for the misunderstanding my english is a bit lame.

Start by detecting your user's OS, with something similar to this:

 var OSName="Unknown OS";

 if (navigator.appVersion.indexOf("Win")!=-1) OSName="Windows";
 if (navigator.appVersion.indexOf("Mac")!=-1) OSName="MacOS";
 if (navigator.appVersion.indexOf("X11")!=-1) OSName="UNIX";
 if (navigator.appVersion.indexOf("Linux")!=-1) OSName="Linux";

document.write('Your OS: '+OSName);

There are many different implementations for this, but I kept it extra simple and it still will work just as well as the 150 line versions.

Next, set your line endings in a variable, depending on the OS returned, and build your string from that. Ie:

if (navigator.appVersion.indexOf("Win")!=-1){
    OSName="Windows";
    linebreak = "\r\n";
} // etc ...
Stephane Gosselin
  • 9,030
  • 5
  • 42
  • 65
  • Line breaks and whitespace are preserved inside PRE elements, but otherwise, you're correct. – RobG May 27 '11 at 06:12
  • I need to insert a line break into a `textarea` programmatically, and wish to do so in an OS-sensitive manner. – davidchambers May 27 '11 at 06:39
  • @davidchambers - Ah, yes I see now, see my revised answer then. – Stephane Gosselin May 27 '11 at 06:45
  • 1
    The operating system doesn't actually dictate this. Opera, for instance, uses `\r\n` even on \*nix. Chrome, Firefox, and Safari use `\n` even on Windows. But fortunately, we can *feature detect* what gets used (see my answer for details). – T.J. Crowder Jul 26 '11 at 17:03
0

if you really want the break element for some reason why don't you just:

var br=document.createElement('br');
Trey
  • 5,480
  • 4
  • 23
  • 30