I have some javascript that manipulates html based on what the user has selected. For real browsers the methods I'm using leverage the "Range" object, obtained as such:
var sel = window.getSelection();
var range = sel.getRangeAt(0);
var content = range.toString();
The content variable contains all the selected text, which works fine. However I'm finding that I cannot detect the newlines in the resulting string. For example:
Selected text is:
abc
def
ghi
range.toString() evaluates to "abcdefghi".
Any search on special characters returns no instance of \n \f \r or even \s. If, however, I write the variable out to an editable control, the line feeds are present again.
Does anyone know what I'm missing?
It may be relevant that these selections and manipulations are on editable divs. The same behaviour is apparent in Chrome, FireFox and Opera. Surprisingly IE needs totally different code anyway, but there aren't any issues there, other than it just being IE.
Many thanks.
Your question is not clear but if you mean why "\n" is not visible as text in js then it is because it is newline character i.e it can be used to get an similar effect as html <br> tag.
The newline character is \n in JavaScript and many other languages. All you need to do is add \n character whenever you require a line break to add a new line to a string.
JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs. You can use spaces, tabs, and newlines freely in your program and you are free to format and indent your programs in a neat and consistent way that makes the code easy to read and understand.
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) :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With