5

Is there anyway to get the next character after a window.getSelection()? I need to check if the character after the selected text is a space or not...

EDIT: Thank you for your answers! I'm basically using this link to highlight text, but would like to limit things to full words. I've used the presented solution below (by Steven) as a starting point; I think that the following should work:

sel = window.getSelection();
var text = sel.anchorNode.nodeValue;
var index = sel.baseOffset + sel.focusOffset-1;
var isSpace = text[index] === undefined;
if (isSpace) {
alert("space");
}

(In the link above, I used this code right after the makeEditableAndHighlight function call).

Community
  • 1
  • 1
Eric
  • 1,209
  • 1
  • 17
  • 34

2 Answers2

2

This is a start, provided there is at least one more character in focusNode:

window.getSelection().focusNode.textContent.charAt(window.getSelection().focusOffset)
stackunderflow
  • 953
  • 7
  • 17
  • I need to do some more testing, but this is looking promising! – Eric May 25 '13 at 22:23
  • This is working for me on Safari. But, after doing some research, I've found that the getSelection() method doesn't work for older browsers. I wonder if I can somehow use Tim Down's rangy... – Eric May 26 '13 at 14:30
1

Try it this way:

var sel = window.getSelection()
var text = sel.anchorNode.nodeValue;
var index = sel.baseOffset + sel.focusOffset;
var isSpace = text[index] === ' ';
Steven Moseley
  • 15,871
  • 4
  • 39
  • 50
dersvenhesse
  • 6,276
  • 2
  • 32
  • 53