4

Given a character index, for example the 42nd character, how can I get at which line and which column that character is in a textarea? Given manual line-breaks and text wrapping.

I've tried iterating through the characters and checking for new lines (\n) to increase the line counter, but I have no idea how to check for automatic wrapping. Even using the cols attribute doesn't seem very reliable for this.

OdraEncoded
  • 3,064
  • 3
  • 20
  • 31
  • 2
    Can you show us what have you've tried? – tptcat Dec 08 '13 at 16:24
  • @tptcat I've tried iterating through the characters and checking for new lines(`\n`) to increase the line counter, but I have no idea how to check for automatic wrapping. Even using the `cols` attribute doesn't seem very reliable for this. – OdraEncoded Dec 08 '13 at 16:30
  • Maybe it would help if you shared with us what you want to do with the line/col # once you find it. The part I'm having trouble understanding is why the line number matters for text wrapping. Since the point at which a line wraps will change depending on the textarea size, and a user can even change that as they type, I guess I'm trying to figure out why that would matter for your example. – tptcat Dec 10 '13 at 14:41
  • Also, this might be a direction to look into?: http://stackoverflow.com/questions/15835327/how-to-find-whether-text-in-a-text-area-is-wrapped-to-multiple-lines and http://stackoverflow.com/questions/4719777/finding-line-breaks-in-textarea-that-is-word-wrapping-arabic-text – tptcat Dec 10 '13 at 17:02

1 Answers1

-2
var line = Math.floor(index / width);
var column = index % width;
Samuel
  • 2,106
  • 1
  • 17
  • 27
  • I'm afraid it's not that easy. – OdraEncoded Dec 08 '13 at 17:28
  • Why not? The width attribute of textarea defines the number of characters per line. Indeed if the text contains several paragraphs, you should add the count of \n to line. Unless you want it to manage user resizes as well... – Samuel Dec 08 '13 at 17:32
  • What about wrapping? And the fact that `cols` is actually unreliable? – OdraEncoded Dec 08 '13 at 17:42