Skip to content

Instantly share code, notes, and snippets.

@rynbyjn
Created June 19, 2014 20:20
Show Gist options
  • Save rynbyjn/ae1ff64a379588a9beb3 to your computer and use it in GitHub Desktop.
Save rynbyjn/ae1ff64a379588a9beb3 to your computer and use it in GitHub Desktop.
Gets the closest word backwards from the cursor position within a text node.
getWordFromSelection: (e) ->
selection = document.getSelection()
word = []
text = selection.anchorNode?.wholeText || ' '
wordArr = text.split('')
anchorPos = selection.anchorOffset - 1
anchorPos = 0 if anchorPos < 0
for index in [anchorPos..0]
letter = wordArr[index]
if letter.match(/\s/)
break
else word.unshift(letter)
word.join('')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment