Javascript to scan words infront and behind the selected word

I am trying to generate a complete sentence in which a word was highlighted using javascript.

window.getSelection 

Get me the highlighted word. I searched for examples of javascript ranges, but still don't fully understand how a loop is, moving the selection backward until punctuation is found, and then forward until punctuation is found.

Example:

Social media has a fraught relationship with neurosis. Intrusive people are important for sites like Facebook and Twitter. They add energy and buzz. Their personalities are tied to their avatars and that in itself makes sites important. They provide most of the content. A study published last fall reported that twenty thousand Twitter users provide half of what they read. But obsessions are dangerous, too. They can make the site seem creepy.

If I chose the word "Facebook" above, my last line should be "Obsessive people are important for sites like Facebook and Twitter."


Update 1:

the code below works, but stops if there are html tags.

Example:

, . - , - 1,6 . , , . - , 0,4%.

"find" , " " " , "

?

+3
2

window.getSelection Selection, Range, , , . :

rng = window.getSelection().getRangeAt(0)
start = rng.startOffset
end = rng.endOffset
text = rng.startContainer.nodeValue

before = text.substr(0, start)
sel = text.substr(start, end - start)
after = text.substr(end)

sentence = before.match(/[^.!?]*$/)[0] +  sel + after.match(/^[^.!?]*/)[0]

FF Chrome, IIRC, MSIE . . http://msdn.microsoft.com/en-us/library/ie/ms535869%28v=vs.85%29.aspx.

+2

All Articles