January 9th, 2013, 07:19 AM
Get text surrounding selected text
Im working on an article spinner in HTML and jQuery. Whenever a user selects a word in the article textarea, you can look up synonyms for it.
To make it more user friendly, I want to show a small part of the text surrounding the selected word in a DIV, so the user will remember for what sentence he is looking for synonyms
However, I can't find a proper way to do this. So the question: how can I retrieve text surrounding a selected word in a textarea?
Is this even possible?
Im using the RangyInputs Library to manipulate selections in the textarea
January 9th, 2013, 07:28 AM
um, haven't you looked into that library yet? There's a getSelection() method, which returns the start and end index of the selection. With that, you can select the corresponding substring of the textarea content.
January 9th, 2013, 07:31 AM
I know, but there is no clean method to get the text between two points without altering the current selection
January 9th, 2013, 07:40 AM
January 9th, 2013, 07:48 AM
How can I use that to get text outside of the current selection?
January 9th, 2013, 08:00 AM
With that, you can get any surrounding text you want. If you want the 5 characters before and after the selection, substract 5 from the start, add 5 to the end, and then use substring() with those two numbers.
January 9th, 2013, 08:23 AM
Thanks! That did it. I got this code now:
var sel = $(\"#txt\").getSelection();
var sentence = $(\"#txt\").val().substring(sel.start - 10,sel.end + 10);
Comments on this post
Last edited by Rhytz; January 9th, 2013 at 08:28 AM.