Problem detecting Newlines in JavaScript Range Object Problem detecting Newlines in JavaScript Range Object javascript javascript

Problem detecting Newlines in JavaScript Range Object


Editing my post:

Experimenting a bit, I find that sel.toString() returns new lines in contenteditable divs, while range.toString() returns newlines correctly in normal non-editable divs, but not in editable ones, as you reported.

Could not find any explanation for the behaviour though.

This is a useful link http://www.quirksmode.org/dom/range_intro.html


I found at least two other ways, so you may still use the range to find the position of the caret in Mozilla.

One way is to call

var documentFragment = rangeObj.cloneContents ();

which holds an array of childNodes, and any line breaks will show as a node of class "HTMLBRElement".


The other way is to make sure every "br" tag is followed by a newline character (0x0a)!

This won't hurt the HTML content in any visible way, but now all HTML breaks are translated to plain text line breaks as soon as range.toString() is being called!


I hope this helps - even if this topic is very old. (I'm a necromancer anyway already, hehe) :)


Thanks to the OP I was able to do it using window.getSelection() as he suggested. I needed to get the text until the caret position on an InputEvent , which gives me a static range with the inserted text. So I have a range but not necessarily the current selection's range.

function richToPoorText(range){    //Caso base, está colapsado.        console.log(range);        var restoreRange=document.createRange(); //needed for restoring the caret pos.        restoreRange.setStart(range[0].endContainer, range[0].endOffset);        restoreRange.setEnd(range[0].endContainer, range[0].endOffset);        rangeClone=document.createRange();        rangeClone.setStart(__baseEditor,0);        rangeClone.setEnd(range[0].endContainer, range[0].endOffset);        var str;        var sel=window.getSelection();        sel.removeAllRanges();        sel.addRange(rangeClone);   //sel does converts the br to newlines        str=sel.toString();        sel.removeAllRanges();        sel.addRange(restoreRange);        return str;}

Thankyou very much OP. And if someone has the same use case, you can use this snipset

Edit: __baseEditor is a global variable pointing to the editor's main contenteditable div