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