How to get line separation from the system

7

Some operating systems (i.e., Windows and BSD) like to break lines with Carriage Return (CR) followed by Line Feed (LF), or \r\n .

While GNU / Linux, OS X and other Unix-like ones usually break only with LF ( \n ).

Is there any way in Javascript to get the line break character of the client system? Any HTML 5 APIs or anything that would allow me to get this without appealing to reading the user agent header of a request, in order to check the operating system?

    
asked by anonymous 15.09.2014 / 21:05

3 answers

2

In the ECMA specification the section 7.3 only defines grammar and possible tokens recognized as line breaks.

As there is no exact way to figure out the characters in the line break. I leave a heuristic to detect the line break style:

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";
}

Second T.J. Crowder in this SO response EN , this function works because browsers that use \r\n do the on-the-fly conversion of \n when they do the parsing of the HTML string.

In addition it is necessary to reinforce that the results can vary for the same OS. Because different browsers do different things.

You can test on JSBin .

    
16.09.2014 / 00:56
3

You can do something very close to what you want without using Javascript. The HTTP header User-Agent includes information about your client's browser and operating system, and your server can look at this when you receive the customer form. It's not 100% accurate, since the value of the User-Agent header is configurable by the user, but at the same time I do not believe there is some 100% sure way to know the client OS.

Of course, another possibility is to add an extra field in your form and ask the customer what type of line break he prefers: P

    
15.09.2014 / 23:53
1

As a practical application, I imagine the idea is to identify the line ending by the OS to be able to exchange for an HTML tag, for example, to show in real time the output of a textarea field (just like in StackOverflow ).

You can use a regular expression that identifies \n (used by * NIX) or \r\n (used by Windows).

htmlstring = stringContainingNewLines.replace(/(\r\n|\n|\r)/gm, "<br>");
    
15.09.2014 / 23:31