Alex
Alex

Reputation: 68036

Detect if the selected text spans on the entire line or more lines

I'm trying to auto-detect if the selection of a textarea contains new lines, or if the full line has been selected.

For example

This will detect the last case:

var range = getTextAreaSelection(textarea),
    selection = textarea.value.substring(range[0], range[1]);

if(selection.indexOf('\n') !== -1)
  // do stuff...

But how do I handle the other two?

Upvotes: 2

Views: 318

Answers (1)

pimvdb
pimvdb

Reputation: 154848

You could check what the character before/after is:

textarea.value.charAt(range[0] - 1); // if it's `\r` or `\n` it's the first char of a line
textarea.value.charAt(range[1] + 1); // same fot last char of a line

If either or both return an empty string, it's the beginning/ending of the textarea value so that would also count as a full line.

Upvotes: 1

Related Questions