views:

402

answers:

1

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.

+1  A: 

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

Narayan Raman
Excellent, yep, sel.toString() has the newlines. Thanks very much!
CodeBadger